10 life-saving PHP snippets

by Jean. 62 Comments -

In order to be efficient, a web developer should have a toolbox with code snippets he can use and reuse when needed. In this article, I’m going to show you 10 extremely useful PHP code snippets to add to your web developer toolbox.

Highlight specific words in a phrase

Sometimes, for example, when displaying search results, it is a great idea to highlight specific words. This is exactly what the following function can do:

function highlight($sString, $aWords) {
	if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
		return false;

	$sWords = implode ('|', $aWords);
 	return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);

Source: http://www.phpsnippets.info/highlights-words-in-a-phrase

Get your average Feedburner subscribers

Recently, Feedburner counts had lots of problems and it’s hard to say that the provided info is still relevant. This code will grab your subscriber count from the last 7 days and will return the average.

function get_average_readers($feed_id,$interval = 7){
	$today = date('Y-m-d', strtotime("now"));
	$ago = date('Y-m-d', strtotime("-".$interval." days"));
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $feed_url);
	$data = curl_exec($ch);
	$xml = new SimpleXMLElement($data);
	$fb = $xml->feed->entry['circulation'];

	$nb = 0;
	foreach($xml->feed->children() as $circ){
		$nb += $circ['circulation'];

	return round($nb/$interval);

Source: http://www.catswhoblog.com/how-to-get-a-more-relevant-feedburner-count

Automatic password creation

Although I personally prefer leaving users to choose their password themselves, a client recently asked me to generate passwords automatically when a new account is created.
The following function is flexible: You can choose the desired length and strength for the password.

function generatePassword($length=9, $strength=0) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength >= 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	if ($strength >= 2) {
		$vowels .= "AEUY";
	if ($strength >= 4) {
		$consonants .= '23456789';
	if ($strength >= 8 ) {
		$vowels .= '@#$%';

	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
	return $password;

Source: http://www.phpsnippets.info/generate-a-password-in-php

Compress multiple CSS files

If you’re using different CSS files on your site, they might take quite long to load. Using PHP, you can compress them into a single file with no unnecessary white spaces or comments.
This snippet has been previously discussed on my “3 ways to compress CSS files using PHP” article.

header('Content-type: text/css');
function compress($buffer) {
  /* remove comments */
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;

/* your css files */


Source: http://www.phpsnippets.info/compress-css-files-using-php

Get short urls for Twitter

Are you on Twitter? If yes, you probably use a url shortener such as bit.ly or TinyUrl to share your favorite blog posts and links on the network.
This snippet take a url as a parameter and will return a short url.

function getTinyUrl($url) {
    return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);

Source: http://www.phpsnippets.info/convert-url-to-tinyurl

Calculate age using date of birth

Pass a birth date to this function, and it will return the age of the person; very useful when building communities or social media sites.

function age($date){
	$year_diff = '';
	$time = strtotime($date);
	if(FALSE === $time){
		return '';

	$date = date('Y-m-d', $time);
	list($year,$month,$day) = explode("-",$date);
	$year_diff = date("Y") – $year;
	$month_diff = date("m") – $month;
	$day_diff = date("d") – $day;
	if ($day_diff < 0 || $month_diff < 0) $year_diff–;

	return $year_diff;

Source: John Karry on http://www.phpsnippets.info/calculate-age-of-a-person-using-date-of-birth

Calculate execution time

For debugging purposes, it is a good thing to be able to calculate the execution time of a script. This is exactly what this piece of code can do.

//Create a variable for start time
$time_start = microtime(true);

// Place your PHP/HTML/JavaScript/CSS/Etc. Here

//Create a variable for end time
$time_end = microtime(true);
//Subtract the two times to get seconds
$time = $time_end - $time_start;

echo 'Script took '.$time.' seconds to execute';

Source: http://phpsnips.com/snippet.php?id=26

Maintenance mode with PHP

When updating your site, it is generally a good thing to temporarily redirect your users to a “Maintenance” page so they will not see any critical info such as error messages.
This is generally done using an .htaccess file, but it can be done easily with PHP:

function maintenance($mode = FALSE){
        if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
            header("Location: http://example.com/maintenance.php");
        if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
            header("Location: http://example.com/");

Source: http://www.phpsnippets.info/easy-maintenance-mode-with-php

Prevent js and css files from being cached

By default, external files such as javascript and css are cached by the browser. If you want to prevent this from caching, simply use this easy tip:

<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" /&glt;

The result will look like this:

<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css" /&glt;

Source: http://davidwalsh.name/prevent-cache

Add (th, st, nd, rd, th) to the end of a number

Another useful snippet which will automatically add st, nd, rd or th after a number.

function make_ranked($rank) {
	$last = substr( $rank, -1 );
	$seclast = substr( $rank, -2, -1 );
	if( $last > 3 || $last == 0 ) $ext = 'th';
	else if( $last == 3 ) $ext = 'rd';
	else if( $last == 2 ) $ext = 'nd';
	else $ext = 'st'; 

	if( $last == 1 && $seclast == 1) $ext = 'th';
	if( $last == 2 && $seclast == 1) $ext = 'th';
	if( $last == 3 && $seclast == 1) $ext = 'th'; 

	return $rank.$ext;

Source: http://phpsnips.com/snippet.php?id=37

Comments (62) - Leave yours

  1. Piero Giusti said:

    “Prevent js and css files from being cached”

    The best way to prevent this, is copy the Rails helper mode.

    link href=”/stylesheet.css?” rel=”stylesheet” type=”text/css”

    • Jonathan said:

      Because without a timestamp date() will use the current time.

      So if it’s say the first of the month you’ll end up with “9st”.

      You’d have to construct a timestamp using mktime() and pass that as the second parameter to get an accurate suffix.

      Which would still be much shorter than the suggested method, although not sure if there would be any performance hit by using mktime() and date() – something to look into methinks.

      Actually, about that last method – I’m surprised there’s no use of MOD (%) to get the last number or ‘teenth’ status, or a switch when checking the numbers – far to many elses.

      RE caching of CSS files, surely one would want them cached to save time and bandwidth? The best thing to do is slap a version number on the end i.e. style.css?v=1.1.5, that way it will be redownloaded when changed, but all other times the cached version (if far future expires has been used) will be used – if developing just hit ctrl+f5.

      • Justin Rovang said:

        I guess I meant more along:

        echo date(‘jS’, strtotime(’0000-00-’.$nDay));

        bad hack still

        • Neel Upadhyaya said:

          Slightly better version of the posted code:
          function make_ranked($rank) {
          $ext = ‘th’;
          if ($rank 20) {
          switch($rank % 10) {
          case 1:
          $ext = ‘st’;
          case 2:
          $ext = ‘nd’;
          case 3:
          $ext = ‘rd’;
          return $rank.$ext;

          • Neel Upadhyaya said:

            The if statement was mutilated by the html sanitiser should be

            if ($rank less than 4 || $rank greater than 20)

  2. Jamie said:

    all very good tips.

    re: Compress multiple CSS files, great tip, but you are going to be loading and compressing the files each time the page loads, I would suggest using this function on your site once completed, outputting the result to a file (style.min.css) and then loading that. Use apache gzip to compress it. Much less strain on the web server.

    • James Logsdon said:

      No, it’s labeled correctly. microtime(true) returns the UNIX time *with* microseconds as a float.

    • James Logsdon said:

      To prevent ambiguous characters from being used. It’s difficult to tell 0 from O (zero from “o”), or I from l (capital “i” from lower-case “L”).

  3. Pradeep said:

    Nice tips, definitely handy.

    Regarding CSS multiple file compression, how does one differentiate between ‘print’ style and ‘main’ style. I assume these styles contain some identical elements and whatever comes later will be displayed.

    Normally we provide a media attribute, but what happens here??

  4. Jonnas said:

    Great php code samples, nice coding. “Calculate execution time” really came handy for my Joomla website, it is really heavy and it requires value of 150 which I didn’t know previous. Great tips, thanks.

  5. Eric Munoz said:

    I thought I was stuck with the site error page during maintenance and found myself very annoyed and also stressed that a potential customer would come across it. I have implemented the snipped with the .htaccess file and voila – now I’m doing “site maintenance” Thanks!!

  6. Jess said:

    Many thanks. There are 3 or 4 listed which for me are great to have around. I love the ‘Swiss pen knife’ aspect of have all these code snippets at my disposal.

  7. Jerry said:

    Great snippets and coding tips, for sure I need to use some of those. Previously I was building websites from scratch, but now all those open source CMS are simply amazing.

  8. Matthias said:

    About the highlight function: I think it’s better if it returns the original string, when $aWords is empty. Otherwise, if there’s nothing to highlight, nothing will be returned.

      • JAzzY said:

        But with cURL you can change the header information & add cookies etc. file_get_contents seems to show errors sometimes that do get annoying after a while, cURL never seems to display errors for me.

        • Paul said:

          Yeah you have all that flexibility in a case where it’s not needed, as for the errors: quick and dirty: @file_get_contents, or custom error handler, or suppress errors since it’s on production.

          • Joakim said:

            The problem is a lot of webhosts have blocked file_get_contents(), since it is considered a security threat. I’ve learned to always use cURL.

  9. kris said:

    The automatic password is genius. I never knew it was possible with just some ‘simple’ php code. I added it to a website of mine. Many thanks.

  10. Jay said:

    the highlight shows errors on my website in the error_log file, it works fine for me however I view the error_log and a few customers must have triggered the error. Why?

    Did they search for a | or something to make it… funny?

    • Charlie said:

      Yes, the error was probably caused by somebody searching for a word containing “|”. On many keyboard layouts the “|” key is beside the shift key and could be hit by mistake. It is also possible they were intentionally searching for “|” but that is unlikely outside of programming related sites.

      The easiest fix is to just strip “|” characters from the $aWords array.

  11. vansci123 said:

    I never knew it was possible with just some ’simple’ php code.I love the ‘Swiss pen knife’ aspect of have all these code snippets at my disposal.

  12. Extension:103 said:

    is php minify and compression a bit useless these days? php comprerssion has a high proccessing habit. personally i just minify the css with a minify script and then send it compressed through htaccess.

  13. Ignacio Lago said:

    Improve the performance of “Prevent js and css files from being cached” using:

    echo $_SERVER['REQUEST_TIME'];

    It’s way better than time(); and almost the same result.

    Notify me if you update the snippet :)

  14. Paul said:

    make_ranked optimized (less ifs, shorter function body):

    function make_ranked($rank) {
    $last = substr( $rank, -1 );
    $seclast = substr( $rank, -2, -1 );

    $ext = ‘th’;
    $ending = array( 1 => ‘st’, 2 => ‘nd’, 3 => ‘rd’ );
    //having the most common case in a variable and substituting the ifs with a short array should be much faster and lighter on the CPU with a very small amount of extra memory used instead until the end of the function

    if( $seclast != 1 && $last <= 3 && $last != 0 ) {
    //we could make an array_key_exists call but I'm not sure it's faster than the last two comparisons separately
    $ext = $ending[$last];

    return $rank.$ext;

  15. Paul said:

    Alternate password generator, pretty safe, pretty unique and not so many calls to rand (mt_rand() is faster and better):

    function generatePassword($length) {
    $password = md5(uniqid(mt_rand(), true));
    return substr($password, 0, $length);
    } //keeping it simple, only hex,

    //want it more complicated:
    function generateBetterPassword($length) {
    $crap = ‘!@#$%^&*;.,/?\|+-_=’; //make the crap whatever you need

    $password = base64_encode(uniqid(mt_rand(), true)); //you can drop mt_rand and / or true to achieve better performance
    $password = str_shuffle($password.$crap);
    return substr($password, 0, $length);
    //this is just a suggestion using mostly only php functions, avoiding for loops and such, uses str_shuffle to mix it up, I used base 64 since it spits out lowercase, uppercase letters and numbers
    //it might be less resource intensive (I don’t know, just thought it’s nice), if not enough you can safely drop the mt_rand() and true from uniq_id and still get pretty good randomness, or keep only the second parameter to have more entropy

  16. Joakim said:

    I like this, especially the highlighting.

    The age function can be radically reduced by using PHP5, and file_get_contents() is often blocked by webhosts.

  17. 5ubliminal said:

    Compress multiple CSS files is a real mess in terms of performance. NEVER include files that are not supposed to be interpreted as PHP. You should use readfile(*.css); instead. Or include(*.css.php).

    require() vs. readfile() for non-PHP contents is at least twice as slow. And, when working with many files, performance is crippled.

  18. Rich said:

    RE: Get short urls for Twitter

    “return file_get_contents(“http://tinyurl.com/api-create.php?url=”.$url);”

    Most likely $url will need to be urlencode($url) or query parameters passed in $url will appear to be part of the twitter URL rather than the passed $url

  19. Neel Upadhyaya said:

    Here’s a smaller version of the age function:
    function age($date) {
    $age = time() – strtotime($date);
    return intval($age / (365.25 * 24 * 60 * 60));

    • 5ubliminal said:

      Man, I wish people validated their stuff. An invalid $date format will give an astronomical age as it will be time() – 0 (actually FALSE or -1). So, you do like this:
      if(($strtm = strtotime($date)) < 1) return false; // Covers both -1 and FALSE
      and then you continue with $age = time() – $strtm; …

  20. John Gilchrist said:

    I like the valuable info you provide in your articles. I will bookmark your weblog and check again here frequently. I am quite certain I will learn many new stuff right here! Best of luck for the next!

  21. cx42net said:

    well, it didn’t displayed correctly, I remove the opening php tags :

    * Create a DateTime object with the given number of seconds
    * @param Integer $iTime : Timestamp in seconds
    * @param String $sFormat (optionel) : The date format to return
    * @return String : The formated date
    function timetostr ($iTime, $sFormat = ‘d\j H\hi\ms\s’) {
    $oTime = new DateTime (‘@’.$iTime);
    return $oTime->format ($sFormat);

    and the adptated snippet :

    timetostr (strtotime($date), ‘Y’);

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!