5 More Useful PHP Snippets

December 14th, 2012 Leave a comment
Like the article?
5 More Useful PHP Snippets

Given the success of our last PHP Snippets article, we’ve decided to go ahead and find a few more useful PHP snippets. Without further ado, here are some more useful (and a bit more complex) PHP snippets for use!

1. Generating CSV

Many people have come up with their own functions for generating CSVs, but the problem is that many of them fail to take into account wayward quotation marks or apostrophes that will bring down their CSV and make it harder to parse later. A much better idea is to take those into account, like so:

function make_csv(array $to_csv, $file = false) { 
	$fstream = ($file)
			? fopen("php://temp/maxmemory", "w+")
			: fopen("php://output", "w"); 

	foreach ($to_csv as $record) {
		fputcsv($fstream, $record);

	if ($file) {
		$x = stream_get_contents($file); 
		return $x; 
	} else {
		return null;

Using this function makes creating CSVs less of a chore and far easier, especially when it comes to stability and reliability of the generated CSVs!

2. Highlight Words In A String

Sometimes it’s extremely handy to highlight words when users are searching for them. Here’s a code snippet to do exactly that!

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

	$aword = implode ('|', $aword);
	return preg_replace ('@\b('.$aword.')\b@si', '<strong style="background-	color:red">$1</strong>', $astring);

3. Shorten URLs

Sometimes you want to shorten URLs when URLs are simply too long and unwieldy. Here’s a code snippet to help you shorten those URLs (this is especially helpful to pop into a share tag on blogs or other pages that get shared often!)

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


This is an incredible piece of code that somebody over at phpsnips (http://phpsnips.com/71/ASCII-CAPTCHA) cooked up- it’s an ASCII captcha! It takes a bit to load but it’s quite secure, and it’s wonderfully creative, innovative, and cool. Take a look at this one:

// Get the fonts for the CAPTCHA 
$fonts = glob('examples/CAPTCHA/fonts/*'); 
// Build a String 
$string = md5(rand(0,5000)); 
// Get the first 4 letters and place it in an array 
$string = substr($string,0,4); 
$letters = str_split($string); 
// Set the CAPTCHA Height 
$ih = 60; 
// Set the CAPTCHA Width 
$iw = 130; 
// Set the Font size 
$fs = 25; 
// Create an image 
$image = imagecreatetruecolor($iw, $ih); 
// Set a default background color 
$white = imagecolorallocate($image, 255, 255, 255); 
// Add the background color to the image 
imagefilledrectangle($image, 0, 0, $iw, $ih, $white); 
// Set minimum letter y position 
$y_min = ($ih / 2) + ($fs / 3) - 10; 
// Set maximum letter y position 
$y_max = ($ih / 2) + ($fs / 3) + 10; 
// Set the letter starting point 
$x = $fs; 
$i = 0; 

// loop through each letter 
foreach($letters as $letter) { 
    // set the angle of the letter random from -45 and 45 
    $angle = rand(-45, 45);

    // set a random y position of the letter using using the above min and max 
    $y = rand($y_min, $y_max); 
    // check to see if this is first letter
    if ($i != 0) {
        $x += $fs;
    // set the color of the letter 
    $font_color = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200)); 
    // choose a random font
    $rand = array_rand($fonts); 
    // sdd letter to the image 
    imagettftext($image, $fs, $angle, $x, $y, $font_color, $fonts[$rand], $letter); 

$black = imagecolorallocate($image, 0, 0, 0); 
echo '<div id="CAPTCHA">'; 

for($h = 0; $h < $ih; $h++) { 
    for($w = 0; $w <= $iw; $w++) { 
        $rgb = imagecolorat($image, $w, $h); 
        $r = ($rgb >> 16) & 0xFF; 
        $g = ($rgb >> 8) & 0xFF; 
        $b = $rgb & 0xFF; 
        if ($w == $iw) { 
            echo '<br />'; 
        } else { 
            echo '<span style="color:rgb('.$r.','.$g.','.$b.');">#</span>'; 
echo '</div>'; 
$_SESSION['CAPTCHA'] = $string; 
    Image String: <?php echo $_SESSION['CAPTCHA']; ?> 

5. Unzip A File

Many times it’s handy to be able to unzip a file in PHP- many people use system() calls to do this, not realizing that PHP has built-in functions to handle compressed files. Take a look below at a little snippet that will unzip for you!

function unzip_file($file, $path) {
	$zipfile = new ZipArchive();
	if ($zip->open($file) !== TRUE) {
		die ('Could not open archive');

	echo 'Archive extracted successfully!;

Hope you can use these few copy-and-go snippets in your PHP application. I’ll keep ’em coming as I find or come up with any further PHP code we can take advantage off without having to use too much of Google bandwidth and our own time!

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
Don't miss another post! Receive updates via email!