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"));
	$feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $feed_url);
	$data = curl_exec($ch);
	curl_close($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');
ob_start("compress");
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 */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');

ob_end_flush();

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($mode){
        if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
            header("Location: http://example.com/maintenance.php");
            exit;
        }
    }else{
        if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
            header("Location: http://example.com/");
            exit;
        }
    }
}

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

  • Pingback: 10 life-saving PHP snippets | [codepotato]

  • http://pierogiusti.com.br Piero Giusti

    “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”

    • http://pierogiusti.com.br Piero Giusti

      The WordPress remove my code.

      Use the function filemtime.

      “/stylesheet.css?filemtime(stylesheet.css);”

      • http://hellologic.com Nathan J. Brauer

        filemtime() is much better, except that on high-load websites, it can use too much processing.

        Another alternative is to use the current revision number or hash for your current live version of your repository.

    • http://absorbtheweb.com/ Nick

      Why would you guys prevent caching. I force caching with .htaccess :)
      By the way, I like the execution time calculator :) Thanks.

      • http://chriseverson.net/ Chris Everson

        Preventing caching is great to do momentarily when pushing out significant updates, or during dev, but yeah, other than that, I’m a fan of the cache.

  • http://etomco.com Tom

    Awesome!

    I’m always partial to the include.

    can’t live without it

    -TK

  • Pingback: === popurls.com === popular today

  • Pingback: PHP Resources | devdevote.com

  • http://Shak.TV Daniel Shakhmundes

    Google is my “web developer toolbox” – thanks for publishing some sweet code snippets to the index ;-)
    Shak

  • http://knowledgecity.com Jae Xavier

    Some of the snippets are more like features rather than life saving. Good resource to have though.

    Thanks

  • http://rovangju.blogspot.com Justin Rovang

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

    Why not:

    $n = 9;
    echo date($n.’S’);

    • http://www.divisionbyzero.co.uk Jonathan

      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

        Echo date(‘jS’, strtotime(’0000-00-’.$day))

      • Justin Rovang

        I guess I meant more along:

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

        bad hack still

        • Neel Upadhyaya

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

          • Neel Upadhyaya

            The if statement was mutilated by the html sanitiser should be

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

  • http://jamielesouef.com Jamie

    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.

  • http://wwebz.com Rehaan

    great stuff now bookmarked Thanks for sharing

  • http://www.liveanime.org helium

    Thanks alot, needed the word highlighting, will test later, hopefully it can cope with phrases too :)

  • http://www.samvloeberghs.be Sam Vloeberghs

    echo ‘Script took ‘.$time.’ seconds to execute’;

    should be

    echo ‘Script took ‘.$time.’ microseconds to execute’;

    • James Logsdon

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

  • http://www.gregbabula.com Greg Babula

    Awesome, thanks a lot for sharing!

  • Pingback: 10 life-saving PHP snippets | theUnseen

  • Pingback: All The Reasons You Should Volunteer Abroad This Year | IQ and Aptitude Tests

  • http://www.corymathews.com CoryMathews

    Why on the “Automatic password creation” are the vowels not all vowels, and missing some and why is $consonants missing some as well?

    • James Logsdon

      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”).

  • Pradeep

    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??

  • http://ebizoffers.net Jonnas

    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.

  • Pingback: Links for July 21, 2010 – jmock.me

  • http://www.cambiumworks.com Eric Munoz

    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!!

  • http://boy-action.net brian james

    true, but i got poor skill on coding:(, hopefully can learn much from this site :P

  • http://www.targetspace.co.uk Jess

    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.

  • http://rssdiary.com Jerry

    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.

  • Pingback: Hunting for links: Friday Find | Premium BuddyPress Themes at BuddyDress

  • http://www.laceytechsolutions.co.uk Ben Lacey

    Nice list of php functions dude!

    I like the date of birth and the word highlighter one the best.
    Keep up the good code!

    Lacey Tech Solutions

  • Matthias

    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.

  • azel

    I’d rather use cURL than file_get_contents for remote urls tho.

    • http://filequake.com Mike Tansey

      Why? cURL is massively overkill and slower and not always available. file_get_contents is all that’s needed…

      • http://mp3drug.com/ JAzzY

        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

          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.

          • http://joakimdahlstrom.com Joakim

            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.

  • http://rollingclothesrack.net kris

    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.

  • http://www.thomascraigconsulting.com Thomas Craig Consulting

    Great tips, thanks for sharing.

  • http://chr.ishenry.com Chris Henry

    I love resources like this. Whenever I’m into a project, there’s nothing more I hate than having to re-invent the wheel to do something common.

  • http://mp3drug.com Jay

    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?

    • http://countsql.com/http://countsql.com Charlie

      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.

  • http://www.360bookmarks.com/ Jones

    really really nice.

  • http://www.inikeairjordan.com vansci123

    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.

  • http://geekier.com Grant

    rather than never caching js/css, it is useful to version them with build & release cycles

    then for each update they are re-cached

  • http://www.extension103.com Extension:103

    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.

  • http://www.ignaciolago.com/ Ignacio Lago

    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 :)

  • http://www.website-design-edinburgh.co.uk Kevin Thomson

    Love the code for average feedburner subscriptions. Didn’t know you could do that. :) Keep the posts coming!

  • Paul

    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;
    }

  • Paul

    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

  • http://joakimdahlstrom.com Joakim

    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.

  • http://twitter.com/5ubliminal 5ubliminal

    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.

  • http://www.innvo.com/ Rich

    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

  • Neel Upadhyaya

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

    • http://twitter.com/5ubliminal 5ubliminal

      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; …

  • http://www.ssdcomparison.net/?tag=flash-memory-cards John Gilchrist

    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!

  • http://www.reflectiv.net cx42net

    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’);