Useful PHP code snippets and functions

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;


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=''></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);


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


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);
       while (!feof($handle)) {
               $contents .= fread($handle, 8192);
       return $contents;


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
	// close archive
	echo 'Archive extracted to directory';


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 == '' || $ip == 'localhost')
            $ip = '';

        $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 = '' . urlencode($ip);
        $ch = curl_init();

        $curl_opt = array(
            CURLOPT_HEADER      => 0,
            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);


        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;
          return $default;



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, '', $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.

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


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


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

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


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

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


  • in the section [Automatic mailto links]

    where is the mailto:// ?

  • 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.

  • Clement

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

  • 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.

    • in that case I agree with you tarcisio gruppi. it is a good but actually better to use prepared statement in any language.

  • Solid stuff. Thanks again.

    Ever seen a snippet for getting the Google parms (e.g., keywords) from a link in from a SERP?

  • Jaimin Vaja

    This is very good stuff!

  • 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.

  • I have a folder ( savefiles ) with pdf files. I want to know how i can get that files to show in my website. Please help

  • Thanks for these, love the site.

  • Very useful! .. I like it