Useful PHP code snippets and functions

by Jean. 12 Comments -

Every web developer should keep useful code snippets in a personal library for future reference. Today, I have compiled the most interesting and useful PHP code snippets I have added to my personal snippet library the last 3 months.

Convert .pdf files to .jpg using PHP and Image Magick

Here is a simple snippet to convert a .pdf file into a .jpg image. This is extremely useful if you need to generate preview images of your .pdf files. Please note, you must have the Image Magick extension installed on your server to use this snippet.

$pdf_file   = './pdf/demo.pdf';
$save_to    = './jpg/demo.jpg';     //make sure that apache has permissions to write in this folder! (common problem)

//execute ImageMagick command 'convert' and convert PDF to JPG with applied settings
exec('convert "'.$pdf_file.'" -colorspace RGB -resize 800 "'.$save_to.'"', $output, $return_var);


if($return_var == 0) {              //if exec successfuly converted pdf to jpg
    print "Conversion OK";
}
else print "Conversion failed.<br />".$output;

Credits: http://snipplr.com/view/48513

Sanitize database inputs

In order to keep your database safe, you have to be very careful about the input you’re going to save. Here is a super handy function which sanitize inputs to make sure you’re not inserting malicious code into your database.

function cleanInput($input) {
 
  $search = array(
    '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
  );
 
    $output = preg_replace($search, '', $input);
    return $output;
  }

function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        }
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    }
    return $output;
}

// Usage:
$bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

  // Also use for getting POST/GET variables
  $_POST = sanitize($_POST);
  $_GET  = sanitize($_GET);

Credits: http://css-tricks.com/snippets/php/sanitize-database-inputs/

Create image data URIs using PHP

Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves a network request for each image, and prevent exposure of directory paths. Please note that IE7 and below are not compatibles with data URIs.

// A few settings
$image = 'cricci.jpg';

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="',$src,'">';

Credits: http://davidwalsh.name/data-uri-php

Generate CSV file from a PHP array

Here is a simple but efficient function to generate a .csv file from a PHP array. The function accept 3 parameters: the data, the csv delimeter (default is a comma) and the csv enclosure (default is a double quote).

function generateCsv($data, $delimiter = ',', $enclosure = '"') {
       $handle = fopen('php://temp', 'r+');
       foreach ($data as $line) {
               fputcsv($handle, $line, $delimiter, $enclosure);
       }
       rewind($handle);
       while (!feof($handle)) {
               $contents .= fread($handle, 8192);
       }
       fclose($handle);
       return $contents;
}

Credits: http://snipplr.com/view/66856/generate-csv-file-from-array-using-php/

Unzip files with PHP

The following function takes two parameters: The .zip file to unzip, and the destination directory.

function unzip_file($file, $destination){
	// create object
	$zip = new ZipArchive() ;
	// open archive
	if ($zip->open($file) !== TRUE) {
		die ('Could not open archive');
	}
	// extract contents to destination directory
	$zip->extractTo($destination);
	// close archive
	$zip->close();
	echo 'Archive extracted to directory';
}

Credits: http://www.catswhocode.com/blog/snippets/unzip-zip-files

Detect location by IP

Here is an useful code snippet to detect the location of a specific IP. The function below takes one IP as a parameter, and returns the location of the IP. If no location is found, UNKNOWN is returned.

function detect_city($ip) {

        $default = 'UNKNOWN';

        if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
            $ip = '8.8.8.8';

        $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';

        $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
        $ch = curl_init();

        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION  => 1,
            CURLOPT_HEADER      => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT   => $curlopt_useragent,
            CURLOPT_URL       => $url,
            CURLOPT_TIMEOUT         => 1,
            CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
        );

        curl_setopt_array($ch, $curl_opt);

        $content = curl_exec($ch);

        if (!is_null($curl_info)) {
            $curl_info = curl_getinfo($ch);
        }

        curl_close($ch);

        if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs) )  {
            $city = $regs[1];
        }
        if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) )  {
            $state = $regs[1];
        }

        if( $city!='' && $state!='' ){
          $location = $city . ', ' . $state;
          return $location;
        }else{
          return $default;
        }

    }

Credits: http://www.catswhocode.com/blog/snippets/detect-location-by-ip

Email error logs to yourself

Error logs are extremely useful, but you have to read them to know if a problem happened. And let’s be honest: When we think everything is fine, we do not look at logs very often.

This function will email you the log when an error has been raised on your site. Very handy to stay in touch with your website activity.

function nettuts_error_handler($number, $message, $file, $line, $vars){
	$email = "
		<p>An error ($number) occurred on line 
		<strong>$line</strong> and in the <strong>file: $file.</strong> 
		<p> $message </p>";
		
	$email .= "<pre>" . print_r($vars, 1) . "</pre>";
	
	$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	
	// Email the error to someone...
	error_log($email, 1, 'you@youremail.com', $headers);

	// Make sure that you decide how to respond to errors (on the user's side)
	// Either echo an error message, or kill the entire project. Up to you...
	// The code below ensures that we only "die" if the error was more than
	// just a NOTICE. 
	if ( ($number !== E_NOTICE) && ($number < 2048) ) {
		die("There was an error. Please try again later.");
	}
}

// We should use our custom function to handle errors.
set_error_handler('nettuts_error_handler');

// Trigger an error... (var doesn't exist)
echo $somevarthatdoesnotexist;

Credits: http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/

Remove Microsoft Word HTML tags

If you’re working with clients, I guess you already had many problems with people pasting text from Microsoft Word, which results in bad markup and various code problems…

The following function takes some nightmarish Word HTML and return a clean HTML output that you can use safely on the web.

function cleanHTML($html) {
$html = ereg_replace("<(/)?(font|span|del|ins)[^>]*>","",$html);

$html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);
$html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);

return $html
}

Credits: http://tim.mackey.ie/CommentView,guid,2ece42de…

Watermark images automatically

If you’re displaying your own images on your websites, chances are that you don’t want to see them everywhere on the web the next day. To prevent image theft and make sure to be credited as the original creator of the image, watermarking them is generally a good idea. The following function allows you to automatically add a watermark on your images.

function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) { 
   list($width, $height) = getimagesize($SourceFile);
   $image_p = imagecreatetruecolor($width, $height);
   $image = imagecreatefromjpeg($SourceFile);
   imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height); 
   $black = imagecolorallocate($image_p, 0, 0, 0);
   $font = 'arial.ttf';
   $font_size = 10; 
   imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);
   if ($DestinationFile<>'') {
      imagejpeg ($image_p, $DestinationFile, 100); 
   } else {
      header('Content-Type: image/jpeg');
      imagejpeg($image_p, null, 100);
   }
   imagedestroy($image); 
   imagedestroy($image_p); 
}

/******** usage **********/
$SourceFile = '/home/user/www/images/image1.jpg';
$DestinationFile = '/home/user/www/images/image1-watermark.jpg'; 
$WaterMarkText = 'Copyright phpJabbers.com';
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);

Credits: http://www.phpjabbers.com/put-watermark-on-images-using-php…

Automatic mailto links

The following snippet looks for an email address in a string, and replace it by a mailto link. Pretty useful on private applications, but for obvious spamming reason I do not recommend using this on a website, blog or forum.

$stringa = "This should format my email address example@domain.com";

$pattern = "/([a-z0-9][_a-z0-9.-]+@([0-9a-z][_0-9a-z-]+\.)+[a-z]{2,6})/i";
$replace = "\\1";
$text = preg_replace($pattern, $replace, $stringa);
echo htmlspecialchars($text);

Credits: http://css-tricks.com/snippets/php/automatic-mailto-links/

Comments (12) - Leave yours

  1. Sam P said:

    The database sanitization snippet seems a little dated as it contains both get_magic_quotes_gpc and mysql_real_escape_string which have been deprecated for some time. (The source was from 2010) Other than that its a good starting point, – just not really useful in a production environment.

  2. Clement said:

    “Remove Microsoft Word HTML tags” is using ereg_* which gave you a warning for a looooong time now and is now deprecated since 5.3.0. The source is from 2005, it should be updated here on catswhocode.

  3. Tarcísio Gruppi said:

    Don’t use mysql_* functions, use PDO.

    It will do all heavy work to make your app secure.

    It’s a good practice to use prepared statements in any language and PDO do that and a lot more.

    PS: Sorry about my english mistakes.

  4. Christophe Debruel said:

    Nice snippets. I tested the location by IP. this line gave an error -> if (!is_null($curl_info)). Which is logic because $curl_info is not declared anywhere. shouldn’t it be something like if (!isset($curl_info) || !is_null($curl_info)).

    Same for the variable $city and $state. the function assumes it will always exist.

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!