10 life-saving PHP snippets

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

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;