05-14-10

10 Productive PHP Functions that You Can Integrate into Your own Applications

The following custom PHP functions have all been pulled from multiple resources, to generate a heartfelt appreciation for all the developers, whom share their program-expertise with the online public.

A small degree of PHP knowledge is expected, to understand what every function is capable of, as I wont be going over them in great detail.

Please submit any advice, code fixes, and|or personal favorites; in the comments section at the bottom of this post. Thank you

1. Random Number

function unique_id($option) {
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    srand((double)microtime()*1000000);
    $i = 1;
    $rand = '' ;
    while ($i <= $option) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $rand = $rand . $tmp;
        $i++;
    }
    return $rand;
}

Although no random number generator can provide 100% accuracy, unless you assess all opposing variables, unique_id() stands very well on its own.

Michael Minter

2. Update Your Twitter Status

function tweetThis($strUsername = '', $strPassword = '', $strMessage = '') {
    if (function_exists('curl_init')) {
        $twitterUsername = trim($strUsername);
        $twitterPassword = trim($strPassword);
        if(strlen($strMessage) > 140) {
            $strMessage = substr($strMessage, 0, 140);
        }
        $twitterStatus = htmlentities(trim(strip_tags($strMessage)));
        if (!empty($twitterUsername) && !empty($twitterPassword) && !empty($twitterStatus)) {
            $strTweetUrl = 'http://www.twitter.com/statuses/update.xml';
            $objCurlHandle = curl_init();
            curl_setopt($objCurlHandle, CURLOPT_URL, "$strTweetUrl");
            curl_setopt($objCurlHandle, CURLOPT_CONNECTTIMEOUT, 2);
            curl_setopt($objCurlHandle, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($objCurlHandle, CURLOPT_POST, 1);
            curl_setopt($objCurlHandle, CURLOPT_POSTFIELDS, "status=$twitterStatus");
            curl_setopt($objCurlHandle, CURLOPT_USERPWD, "$twitterUsername:$twitterPassword");
            $result = curl_exec($objCurlHandle);
            $arrResult = curl_getinfo($objCurlHandle);
            if ($arrResult['http_code'] == 200) {
                echo 'Your Tweet has been posted';
            }  else {
                echo 'Could not post your Tweet to Twitter.';
            }
            curl_close($objCurlHandle);
        } else {
            echo('Missing required information to submit your Tweet.');
        }
    } else {
        echo('Curl Extension is not installed.');
    }
}

tweetThis() adds direct glorification of being able to Tweet on a moment’s notice. Should be a privilege to use in existing functions to autonomously update followers of unique actions or as a manual social network plug-in.

Richard Castera

4. Shorten a URL with TinyURL

function ShortURL($toConvert) {
    $shortURL= file_get_contents('http://tinyurl.com/api-create.php?url=' . $toConvert);
    return $shortURL;
}

shortURL() will go well (intentionally) with the tweetThis() function, listed above, if you know that you’ll be using long links.

Snipplr.com

3. Replace bad Words

function ReplaceBadWords($str, $bad_words, $replace_str){
    if (!is_array($bad_words)){ $bad_words = explode(',', $bad_words); }
    for ($x=0; $x < count($bad_words); $x++){
        $fix = isset($bad_words[$x]) ? $bad_words[$x] : '';
        $_replace_str = $replace_str;
        if (strlen($replace_str)==1){
            $_replace_str = str_pad($_replace_str, strlen($fix), $replace_str);
        }
        $str = preg_replace('/'.$fix.'/i', $_replace_str, $str);
    }
    return $str;
}
$bad_words = array('fanny','socialism');
echo ReplaceBadWords($str, $bad_words, $replace_str);

I do not condone censorship in any medium. Although I’m still certain that you can find some excuse to modify and use ReplaceBadWords() in some of your work.

Jonas John

5. Capitalize the first Word of every Sentence

function uc_sentences($sString) {
    $sString = strtolower($sString);
    $words = split(" ", $sString); // each entry in array $words is a word from the string
    $firstword = false;
    $sNewString = "";
    foreach($words AS $wordkey=>$word) {
        $word = trim($word); // just in case people double-space between sentences
        $lastchar = substr($word, -1); // $lastchar is used to determine if end-of-sentence is here
        if(($firstword) OR ($wordkey==0)) { // if it's the start of sentence then we capitalize the word
            $word = ucfirst($word);
            $firstword = false;
            $sNewString = $sNewString . " $word"; // add the word to the output string
        } elseif(($lastchar==".") OR($lastchar=="!") OR ($lastchar=="?")) { // you can add more chars if you need to
            $firstword = true; // now the next word will be first word of new sentence
            $sNewString = $sNewString . " $word"; // add the word to the output string
        } else {
            $sNewString = $sNewString . " $word"; // add the word to the output string
        }
    }
    $sNewString = trim($sNewString); // sometimes an extra space at beginning or end occurs, so this fixes it
    return $sNewString; // return the new string
}

$badstring = "I LIKE TO EAT POTATO CHIPS. GO EAT POTATO CHIPS! WHERE ARE THE CHIPS?"; // example string
print uc_sentences($badstring); // this will print "I like to eat potato chips. Go eat potato chips. Where are the potato chips?"

uc_sentences() comes in real handy when dealing with dynamic paragraphs from any user submitted data. I use this consistently with customizable “About me” sections of a website.

PHPBuilder.com

6. Force file download

function force_download($file) {
    if ((isset($file))&&(file_exists($file))) {
        header("Content-length: ".filesize($file));
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        readfile("$file");
    } else {
        echo "No file selected";
    }
}

Do you want to provide a download for a file that needs to be rendered in another format, or requires a function to count the instances in which it’s called, than you’ll want to use force_download(). Easy to call, with a simple, download.php?file=$file.

WebDeveloperPlus.com

7. Add notation to the end of numbers

function ordinal($num){
    $test_c = abs($num) % 10;
    $ext = ((abs($num) %100 < 21 && abs($num) %100 > 4) ? 'th'
        : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1)
        ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
    return $num.$ext;
}

When I need to call a stamped number like this, I usually write out something out with date(). But ordinal(), I expect, would be a great resource for working with any kind of mathematical or scientific features.

PHPSnippets

8. Truncate a string

function truncate($text, $limit = 25, $ending = '...') {
    if (strlen($text) > $limit) {
        $text = strip_tags($text);
        $text = substr($text, 0, $limit);
        $text = substr($text, 0, -(strlen(strrchr($text, ' '))));
        $text = $text . $ending;
    }
    return $text;
}

truncate() takes a string and shortens it to a defined length. If the maximum character length falls in the middle of a word then the function moves the pointer to the previous space. Finishes by appending an ellipsis (or custom string) to the end.

Miles Johnson

9. Simple hit-counter counter

function hits() {
    if (!file_exists('./hits.txt')) {
        $hits = 0;
        file_put_contents('./hits.txt', $hits);
    } else {
        $hits = file_get_contents('./hits.txt');
        $hits = hits + 1;
        file_put_contents('./hits.txt', $hits);
    }
    return $hits;
}
echo hits();

hits() is about as easy as it gets. But as I do, as often as possible, I hope that you take most of the code you get from the Internet and make it more accessible to your tastes anyhow.

PHPSnaps.com

10. Dollar format

function dollar_format($amount) {
    if (preg_match('/^([0-9]+\.[0-9])$/', $amount)) {
       $newAmount = money_format('%.2n', $amount);
    } else {
       $newAmount = $amount;
   }
   return $newAmount;
}

There is a few different methods available to print formatted numbers to show like money. But I recently needed something that only printed the change as change was required. The result is dollar_format().

Michael Minter

04-22-10

Pre-Render Dynamically Resized Images with the PHP-GD Library

If you’ve been frustrated with having to resize images for the sake of continuity or load time and don’t want to develop an entire caching system than this post will be of great value to you.

Today I will discusses the theory and resolve of applying a system to autonomously resize images, with the GD library for PHP, before they get requested by the browser.

This practice presents many benefits to its use.

  1. Save loads of hard drive space
  2. Easy to resize div backgrounds
  3. Faster to call than the use of JavaScript.

Calling the Application With HTML

<img src="image.php?i=image.jpg&s=500" />

Calling the php script is this easy. You can place this tag anywhere on any page and be able to display an image, with exact value constraints, and as many times as you need.

Developing the image.php Application

header("Content-Type: image/jpeg");

header() will make sure that the browser is aware how to handle the applicaton. Here it enables the page to be viewed as a jpeg source.

if (!isset($_GET['s'])) {
    $size = 160;
} else {
    $size = $_GET['s'];
}
$image = $_GET['i'];

list($width, $height) = getimagesize($image);

$ratio = $width/$height;

if ($ratio > 1) {
    $newWidth  = $size;
    $newHeight = $size/$ratio;
} else {
    $newHeight = $size;
    $newWidth  = $size*$ratio;
}
// creates a copy of the loaded image
$create = imagecreatefromjpeg($image);
// creates a blank template to work from
$template = imagecreatetruecolor($newWidth,$newHeight);
// copies the original onto the new template
imagecopyresized($template, $create, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// displays the image
ImageJpeg($template);

Usually I break this larger portion of my post up into smaller pieces so I can reference all the code being used and what it does. But the fundamentals are so well noted and easy to navigate, that I figured even if I left it as so, that you should have no problem implementing this into your own work.

Error catching

If source material is not working properly. Issue the following:

if(!function_exists('imagecreatetruecolor')) {
    exit('Err, function : imagecreatetruecolor does not exist');
}

function_exists() will check the currently active Apache function repository, both internal and user-defined, to see if the listed function matches anything available.

If you’re receiving the error message than the server you’re running this code on does not support the GD library and you must either set it up manually or contact an administrator to do so for you.

Also note that only Jpeg formats are acceptable by this set up. Extending is not a difficult task. I only wanted you to understand the basics and be able to evolve with PHP from my writings.

Summary

Hopefully I’ve left more than enough room for you to adapt this into your own projects. You can add on to this with many of the GD library features documented by the PHP network.

If you develop an extension or even a class, from these tips, please feel free to share by commenting back and letting me know what you’ve done.

04-03-10

Bare-bones way of using Paypal’s Express Checkout NVP API with PHP

I don’t know why Paypal has written its documentation on the subject of, using the Express Checkout name value pair API with PHP, with such an unreadable manner. The classes used with the Paypal API are extremely easy to use. All of this is likely contributing to the confusion about using Express Checkout. But I’m here now, to save your application, and possibly your sanity.

I’m going to explain why the API objects work and what happens when they’re called. There’s a few different ways that you could go about setting up the product and or service details. So I’ll keep this post relative to the main focus points and let you handle the before and after parts on an individual basis.

Referring payment authentication

$paypal = new SetExpressCheckout($totalPrice);

We start out by calling the SetExpressCheckOut() class. It contains the functions you’ll use to redirect the customer to Paypal along with data to differentiate each customer at the completion of the sale. A variable of the total price has to be set to complete the initiation of this class.

$paypal->setNVP("RETURNURL", "http://yourURL.com/confirm.php");
$paypal->setNVP("HDRIMG", "http://yourURL.com/image.jpg");
$paypal->setNVP("EMAIL", "$userEmail"); // customer's email
$paypal->setNVP("AMT", $totalPrice);
$paypal->setNVP("SHIPPINGAMT", "32");
$paypal->setNVP("CUSTOM", "Anything you want to put");
$paypal->setNVP("INVNUM", $uniqueID); // personal invoice number

Before you submit for a transfer to Paypal, know that there are optional values you can send with the setNVP() function, to customize the payment process. All values that can be found, by default, in the etc/NVP/SetExpressCheckout.ini file. I’ve included a list of common practice examples and how to use them in this template.

$paypal->getResponse();

getResponse() sends the user’s browser to Paypal for authentication of credit information. Specifically to a URL that you’ll have to variably set between test mode (sandbox) and live, in the file named etc/NVP/PayPalNVP.ini.

Completing the Sale

$paypal = new GetExpressCheckoutDetails;
$details = $paypal->getResponse();

GetExpressCheckoutDetails() is a class that is most responsible for presenting the custom specifications that you originally sent with SetExpressCheckOut() and SetNVP().

getResponse() will gather all of the available options as an array, labelled $details.

$payment = new DoExpressCheckoutPayment($totalPrice);
$response = $payment->getResponse();

DoExpressCheckoutPayment() will instinctively initiate a communication with Paypal to notify the service that you are ready for the payment to be transferred to your account. The only necessary requisite, of calling this class and it calling to action, is to include the total price in its variable containment field.

getResponse() will gather the resulting responses by DoExpressCheckoutPayment() and include them in an array, labelled $response.

It could be said that you could apply another (final) verification for your customer to submit before the transaction is completed by DoExpressCheckoutPayment(). But not technically necessary.

if ($response['PAYMENTSTATUS'] == 'Completed') {
    //process information
}

One of the returned values in $response will be the PAYMENTSTATUS key. This is a string result that confirms whether or not the money has made been payed to your account. It will definitely be useful when you set up your system to print an invoice on complete, or some insightfully-formatted summary on failure.

Displaying results from getRespnse

echo '<pre>';
print_r($details);
echo '<pre>';
print_r($payment_response);

The above code should print out something similar to the following:

Array
(
    [TOKEN] => EC%2d8DS53628GJ4630109
    [TIMESTAMP] => 2010%2d03%2d31T08%3a25%3a40Z
    [CORRELATIONID] => ce3e460d38d2f
    [ACK] => Success
    [VERSION] => 51%2e0
    [BUILD] => 1247606
    [EMAIL] => test_acct_36654645742_per%40domain%2ecom
    [PAYERID] => W96GXTA5P9BRN
    [PAYERSTATUS] => verified
    [FIRSTNAME] => Test
    [LASTNAME] => User
    [COUNTRYCODE] => US
    [SHIPTONAME] => Test%20User
    [SHIPTOSTREET] => 1%20Main%20St
    [SHIPTOCITY] => San%20Jose
    [SHIPTOSTATE] => CA
    [SHIPTOZIP] => 95131
    [SHIPTOCOUNTRYCODE] => US
    [SHIPTOCOUNTRYNAME] => United%20States
    [ADDRESSSTATUS] => Confirmed
    [CUSTOM] => Anything you want to put
    [INVNUM] => IYUUFEOAS0ME3MTI
)
Array
(
    [TOKEN] => EC%2d8DS53628GJ4630109
    [TIMESTAMP] => 2010%2d03%2d31T08%3a25%3a43Z
    [CORRELATIONID] => b1989df39a0ca
    [ACK] => Success
    [VERSION] => 51%2e0
    [BUILD] => 1247606
    [TRANSACTIONID] => 1PR0061154034542X
    [TRANSACTIONTYPE] => expresscheckout
    [PAYMENTTYPE] => instant
    [ORDERTIME] => 2010%2d03%2d31T08%3a25%3a42Z
    [AMT] => 152%2e00
    [FEEAMT] => 4%2e71
    [TAXAMT] => 0%2e00
    [CURRENCYCODE] => USD
    [PAYMENTSTATUS] => Completed
    [PENDINGREASON] => None
    [REASONCODE] => None
)

Testing

If you don’t have a Paypal developer account, than you should certainly sign up for one to use Paypal’s Sandbox, which makes a mock version of Paypal available for testing. Comes complete with personal and business accounts, each with their own credentials, and unlimited funds.

Summary

Follow the preceding order and you could easily narrow this code down to a a single file, with enough if() constructs, or span it out to many.

You might be left wondering why it seems less daunting than you have expected. That would be because you’re right. These few objects are all that’s needed to handle a shopping cart system on your website.

Maybe Paypal will use this post to refer new users trying to understand how this system works. But I doubt it.

Download now (.zip)

03-25-10

Analysis of Slow Response Times With Javascript Versus PHP

I can only presume that it’s because of the passionate advent of JQuery, that there has been an increasing rise of using Javascript, in precedence of PHP. This circumstance is arguably the sole cause to how and why designers are simply not learning a better way. I’m here to enlighten you.

In opening, I’d like to express, that I hold no animosity for Javascript. Actually I quite often fancy a touch of its elegant lure and almost regularly indulge my viewers with its properties to control aesthetics at a dynamic fashion. But it has its place. If PHP can serve the same purpose, than its obvious strengths, should not be taken for granted.

One prominent example of this that I seem to notice more often in use than others, is the  application of color alternating rows with HTML tables, or also favorably known as the “zebra” effect. Which I’ll be using for my reference material.

Zebra With PHP

for ($i = 1;$i < 10;$i++) {
    if (($i % 2) == 0) {
        echo '<tr class="zebra">';
    } else {
        echo '<tr>';
    }
}

The for() loop, does the accumulating work. It exponentially raises the default value ($i) by one, each iteration, so that the modulus operator (%) can equate the remainder of $i divided by two. So every instance of an even number represented by $i would evaluate to zero.

Zebra With JQuery

$(document).ready(function(){
    $("tr:even").css("background-color", "#EFEFEF");
    $("tr:odd").css("background-color", "#FFFFFF");
});

The JQuery even and odd filters are used as index selectors. This method can be used on any page element with just a little bit of reverse engineering.

Discovering the Front-End

If you were to analyze the speed of using only Javascript, you would find that it is 16% slower, compared to PHP [1]. Though that number might seem relatively low in scale, because it is, consider all of the other factors when developing for the web.

80% of the average user’s response time is spent on the front-end [2]. This time, is composed of downloading all of the elements necessary to make up the page (Images, libraries, scripts, stylesheets and more). Reducing the number of elements, in turn, reduces the number of HTTP requests required to render the page.

With PHP everything is rendered before any HTTP requests are sent by the server.

Graphically interpreted above are the details associated with load times. This analysis completes the HTTP request cycle from initialization. The darker portion, of each representation, shows the percentage of work involved by the server. As consistency shows, a lot of web design and development, relies mostly on what’s being delivered to the browser.

Summary

It’s certain that a professional web server is going to best the average home network set-up, in performance, any day. It’s your responsibility to take advantage of that, by running some server-side code, to save your guests the frustration of dealing with an idle load time.

References

[1] http://www.timestretch.com/FractalBenchmark.html
[2] http://developer.yahoo.net/blog/archives/2007/03/high_performanc.html

03-24-10

The Most Simple Way to Implement A Flickr Gallery With PHP

In my search for finding a simple solution to any problem, I usually cross many and many blogs and articles, discussing my queried topic. But with so much detail that the solution becomes a problem in itself. So I often times end up resolved to research on my own. In this case, I share how to build the most simple method of displaying a Flickr gallery, with PHP.

Assembling Your Variables

$api = 'your-32-byte-api-key-courtesy-Flickr';
$user_id = '33822702%40N08';
$per_page = 10;

The $api key allows your server and Flickr to “shake hands” sort of speak. You can get your Flickr API key here.

Your $user_id is a static variable that Flickr uses to identify you. This value can be found in the URL of your “photostream”. I’ve left mine for reference (flickr.com).

$per_page refers to how many photos will be retrieved from your photostream. Though this limiter is optional, the default count is, “all”. Which means if you have 1,000 plus photos, it could be a very bad thing, for you or your viewer’s load time.

$xml = 'http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key='.$api.'&user_id='.$user_id.'&per_page='.$per_page;

$xml stores the link, that gets called on to retrieve a list of your photos, as XML. This will also be a part of the script you modify to extend the features of your application based on what’s available in the Flickr API.

$flickr = simplexml_load_file($xml);
foreach($flickr->photos->photo as $p) {
    echo '<a href="http://www.flickr.com/photos/'.$p['owner'].'/'.$p['id'].'">';
    echo '<img src="http://farm'.$p['farm'].'.static.flickr.com/'.$p['server'].'/'.$p['id'].'_'.$p['secret'].'_s.jpg">';
    echo '</a>';
}

$flickr uses a PHP function called, simplexml_load_file(), which interprets an XML file into an object. In this case, $flickr, becomes an array, and we use foreach() to extract the values we need, to display the gallery.

Summary

This method is just what I needed. Something small, easily accessible, and scalable. As you experiment with this script, you’ll afford the opportunity to use many tools, which Flickr offers. You can view a full list here if or when you’re ready.

Download Script (.zip)