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

One Comment on “10 Productive PHP Functions that You Can Integrate into Your own Applications”

  • Howard Yeend

    re: unique_id – there’s also http://uk3.php.net/manual/en/function.uniqid.php

    Your version has more options in that you can supply a length though.

    uc_sentences is a nice idea. Here’s a simpler way of doing it:

    function uc_sentences($text) {

    $sentences = preg_split(“/([\.\?\!]\s*)/”, $text, null, PREG_SPLIT_DELIM_CAPTURE);

    $output = “”;
    foreach($sentences as $sentence) {
    $output .= ucfirst($sentence);
    }

    return $output;
    }

    echo “[".uc_sentences(" hi.i like to eat potato chips. go eat potato chips! where are the chips? here they are")."]“;

    Hope the code comes out ok.

    07-30-10 » 8:27 am »

Leave a Comment