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

 

36 Comments

  1. Posted July 19, 2010 at 10:58 am | Permalink

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

    • Posted July 19, 2010 at 11:00 am | Permalink

      The Wordpress remove my code.

      Use the function filemtime.

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

      • Posted July 19, 2010 at 10:16 pm | Permalink

        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.

    • Posted July 27, 2010 at 7:20 am | Permalink

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

  2. Posted July 19, 2010 at 12:26 pm | Permalink

    Awesome!

    I’m always partial to the include.

    can’t live without it

    -TK

  3. Posted July 19, 2010 at 4:36 pm | Permalink

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

  4. Posted July 19, 2010 at 4:48 pm | Permalink

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

    Thanks

  5. Posted July 19, 2010 at 5:35 pm | Permalink

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

    Why not:

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

    • Posted July 20, 2010 at 3:50 am | Permalink

      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
        Posted July 20, 2010 at 7:28 pm | Permalink

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

      • Justin Rovang
        Posted July 20, 2010 at 7:33 pm | Permalink

        I guess I meant more along:

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

        bad hack still

  6. Posted July 19, 2010 at 7:06 pm | Permalink

    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.

  7. Posted July 20, 2010 at 2:32 am | Permalink

    great stuff now bookmarked Thanks for sharing

  8. Posted July 20, 2010 at 4:12 am | Permalink

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

  9. Posted July 20, 2010 at 4:21 am | Permalink

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

    should be

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

    • James Logsdon
      Posted July 21, 2010 at 3:10 pm | Permalink

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

  10. Posted July 20, 2010 at 6:51 am | Permalink

    Awesome, thanks a lot for sharing!

  11. Posted July 20, 2010 at 2:51 pm | Permalink

    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
      Posted July 21, 2010 at 3:11 pm | Permalink

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

  12. Pradeep
    Posted July 20, 2010 at 4:56 pm | Permalink

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

  13. Posted July 21, 2010 at 2:46 am | Permalink

    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.

  14. Posted July 22, 2010 at 2:18 pm | Permalink

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

  15. Posted July 23, 2010 at 1:39 am | Permalink

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

  16. Posted July 23, 2010 at 5:11 am | Permalink

    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.

  17. Posted July 23, 2010 at 6:43 am | Permalink

    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.

  18. Posted July 25, 2010 at 1:42 pm | Permalink

    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

  19. Matthias
    Posted July 26, 2010 at 5:31 am | Permalink

    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.

  20. azel
    Posted July 29, 2010 at 10:55 am | Permalink

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

  21. Posted July 30, 2010 at 3:11 pm | Permalink

    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.

  22. Posted July 31, 2010 at 6:07 am | Permalink

    Great tips, thanks for sharing.

  23. Posted July 31, 2010 at 2:11 pm | Permalink

    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.

  24. Posted August 2, 2010 at 7:53 am | Permalink

    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?

    • Posted August 10, 2010 at 6:42 am | Permalink

      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.

  25. Posted August 3, 2010 at 1:42 am | Permalink

    really really nice.

  26. Posted August 10, 2010 at 4:26 am | Permalink

    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.

  27. Posted July 20, 2010 at 2:25 am | Permalink

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

7 Trackbacks

  1. By 10 life-saving PHP snippets | [codepotato] on July 19, 2010 at 10:13 am

    [...] 10 life-saving PHP snippets Posted July 19th, 2010 in Blog by Gareth http://www.catswhocode.com/blog/10-life-saving-php-snippets?utm_source=twitte…; [...]

  2. By === popurls.com === popular today on July 19, 2010 at 12:41 pm

    === popurls.com === popular today…

    yeah! this story has entered the popular today section on popurls.com…

  3. By PHP Resources | devdevote.com on July 19, 2010 at 4:13 pm

    [...] Cats who code – PHP snippets [...]

  4. By 10 life-saving PHP snippets | theUnseen on July 20, 2010 at 7:16 am

    [...] http://www.catswhocode.com/blog/10-life-saving-php-snippets Like Unlike share this with your people [...]

  5. [...] 10 life-saving PHP snippets [...]

  6. By Links for July 21, 2010 – jmock.me on July 21, 2010 at 11:21 am

    [...] 10 life-saving PHP snippets [...]

  7. [...] Cats who code has a great article on ‘10 life saving PHP snippets’. [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
  • Hosted by VPS.net and Akamai CDN
WordPress Appliance - Powered by TurnKey Linux