10 awesome PHP functions and snippets

by Jean. 33 Comments -

Every web developer should keep useful code snippets in a personal library for future reference. Today, I’m showing you the 10 most useful snippets and functions I have added to my snippet library from the past 3 months.

Sanitize database inputs

When inserting data in your database, you have to be really careful about SQL injections and other attempts to insert malicious data into the db. The function below is probably the most complete and efficient way to sanitize a string before using it with 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;
  }
?>
<?php
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;
}

Here’s some examples of use:

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

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

Calculate distance between two points

Want to be able to calculate the distance between two points? The function below use the latitude and longitude of two locations, and calculate the distance between them in both miles and metric units.

function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $feet = $miles * 5280;
    $yards = $feet / 3;
    $kilometers = $miles * 1.609344;
    $meters = $kilometers * 1000;
    return compact('miles','feet','yards','kilometers','meters'); 
}

Example:

$point1 = array('lat' => 40.770623, 'long' => -73.964367);
$point2 = array('lat' => 40.758224, 'long' => -73.917404);
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
foreach ($distance as $unit => $value) {
    echo $unit.': '.number_format($value,4).'<br />';
}

Source: http://www.inkplant.com/code/calculate-the-distance-between-two-points.php

Get all tweets of a specific hashtag

Here’s a quick and easy way to get all tweets of a specific usage using the useful cURL library. The following example will retrieve all tweets with the #cat hashtag.

function getTweets($hash_tag) {

    $url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ;
    echo "<p>Connecting to <strong>$url</strong> ...</p>";
    $ch = curl_init($url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $xml = curl_exec ($ch);
    curl_close ($ch);

    //If you want to see the response from Twitter, uncomment this next part out:
    //echo "<p>Response:</p>";
    //echo "<pre>".htmlspecialchars($xml)."</pre>";

    $affected = 0;
    $twelement = new SimpleXMLElement($xml);
    foreach ($twelement->entry as $entry) {
        $text = trim($entry->title);
        $author = trim($entry->author->name);
        $time = strtotime($entry->published);
        $id = $entry->id;
        echo "<p>Tweet from ".$author.": <strong>".$text."</strong>  <em>Posted ".date('n/j/y g:i a',$time)."</em></p>";
    }

    return true ;
}

getTweets('#cats');

Source: http://www.inkplant.com/code/get-twitter-posts-by-hashtag.php

Applying Even/Odd Classes

When generating lists or tables using php, it is super useful to apply even/odd classes to each row of data in order to simplify CSS styling.

Used inside a loop, class names would be named .example-class0 and .example-class1 alternating. Increasing the “2″ number allows you to increment in thirds or fourths or whatever you need:

<div class="example-class<?php echo ($xyz++%2); ?>">

Source: http://css-tricks.com/snippets/php/applying-evenodd-classes/

Email error logs to yourself

Instead of publicly displaying possible errors on your website, why not using a custom error handler to email error logs to yourself? Here’s a handy code snippet to do it.

<?php

// Our custom error handler
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;

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

Automatically creates variables with the same name as the key in the POST array

This snippet is very helpful for every POST processing. All you need is an array with expected keys in the POST array. This snippet automatically creates variables with the same name as the key in the POST array. If the key is not found in the POST array the variable is set to NULL. Basically you dont need to write:

$username=$_POST["username"];
$age=$_POST["age"];
etc.

This snippet will do this boring part of every PHP code with POST handling so you can fully focus on a validation of the input, because that is much more important.

<?php
$expected=array('username','age','city','street');
foreach($expected as $key){
    if(!empty($_POST[$key])){
        ${key}=$_POST[$key];
    }
    else{
        ${key}=NULL;
    }
}
?>

Source: http://www.catswhocode.com/blog/snippets/automatically-creates-variables…

Download & save a remote image on your server using PHP

Here’s a super easy and efficient way to download a remote image and save it on your own server.

$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //save the image on your server

Source: http://www.catswhocode.com/blog/snippets/download-save-a-remote-image…

Create data uri’s

Data uri’s can be useful for embedding images into HTML/CSS/JS to save on HTTP requests, at the cost of maintainability. You can use online tools to create data uri’s, or you can use the simple PHP function below:

function data_uri($file, $mime) {
  $contents=file_get_contents($file);
  $base64=base64_encode($contents);
  echo "data:$mime;base64,$base64";
}

Source: http://css-tricks.com/snippets/php/create-data-uris/

Detect browser language

When developing a multilingual website, I really like to retrieve the browser language and use this language as the default language for my website. Here’s how I get the language used by the client browser:

function get_client_language($availableLanguages, $default='en'){
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

		foreach ($langs as $value){
			$choice=substr($value,0,2);
			if(in_array($choice, $availableLanguages)){
				return $choice;
			}
		}
	} 
	return $default;
}

Source: http://snipplr.com/view/12631/detect-browser-language/php-detect-browser-language

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

This simple and easy function will take a number and add “th, st, nd, rd, th” after it. Very useful!

function ordinal($cdnl){ 
    $test_c = abs($cdnl) % 10; 
    $ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th' 
            : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) 
            ? 'th' : 'st' : 'nd' : 'rd' : 'th')); 
    return $cdnl.$ext; 
}  
for($i=1;$i<100;$i++){ 
    echo ordinal($i).'<br>'; 
} 

Source: http://phpsnips.com/snip-37

  • tareq

    hi, thanks for the nice post . on the “Automatically creates variables with the same name as the key in the POST array” , you can also use

    extract($_POST);

    that will do the same but not the validation of course

    • Tielenaar

      No, because there will not be any validation on all the created variables. You might as well switch register_globals on.

      • Anoying

        Best validation with extract($_POST); -> DO NOT USE THE VAR

      • Jason Hazel

        Using a combination of array_intersect and extract, in my opinion, is a hell of a lot better than a loop with a nested if statement.

  • http://www.nyamsprod.com/ nyamsprod

    In 2013, you should definitely avoid what you are suggesting in your first snippets (Sanitize database inputs) there are better approaches like:

    Using native functions in PHP to filter incoming variables (http://www.php.net/manual/en/ref.filter.php)
    Then depending on the extension you use to connect to your database the sanitize the filtered variable accordingly. If you are connecting to a MySQL database it is recommend to use PDO or MySQLi (http://php.net/manual/en/mysqlinfo.api.choosing.php)

    An even better solution is to use a framework or a library that just do that for you I’d suggest using a popular library or components to handle that for you. You could use filterus (https://github.com/ircmaxell/filterus) for filtering, and (https://github.com/auraphp/Aura.Sql) Aura SQL for example

  • vahid

    Very Useful.
    Thanks.

  • http://www.nyamsprod.com/ nyamsprod

    Automatically creates variables with the same name as the key in the POST array.
    Your code could be improve what happend if $_POST['foo'] = false; ideally you should have $foo = false; but with your code it won’t happen.
    $expected = array('username', 'age', 'city', 'street');
    foreach ($expected as $key) {
    ${key} = null;
    if (array_key_exist($key, $_POST)) {
    ${key} = $_POST[$key];
    }
    }

    This should to the trick. But remember that you still need to sanitize the resulting value otherwise your code is still vulnerable.

    • Chris

      Using array_key_exists is slow. Instead you should use if (isset($_POST[$key])) {

  • KingCrunch

    Are you kidding?
    Some of the “snippets” I consider harmful, others are trivial. Really: “file_get_contents()” followed by “file_put_contents()”? a “die()” within an error-handler?

  • http://www.findthiss.com Virneto

    Hey, thats just another great post!! I’ll be using at leat 3 of those right away!!! Thanks a lot!!!
    Cheers to you!!

  • http://www.spinxwebdesign.com/ Alan Smith

    “Calculate distance between two points” this one will help me lot in my website

  • Jony

    For “Applying Even/Odd Classes”,
    <div class="example-class”>
    I think the operation above is not efficient.

    I usually do it like this:
    $xyz = 1 – $xyz;
    <div class="example-class”>
    No need to increment then calculate its mod. But of course this only works if you’re alternating between 2 css class only.

  • Ivan Nikulin

    Odd or even could be checken even simpler.

    1 === ($foo & 1) // if $foo is odd
    0 === ($foo & 1) // if $foo is even

    • http://www.rachiddev.me Rachid

      Even simplier, you can do it with CSS3 :
      tr:nth-of-type(even) { background-color: blue; }

  • Wilson Corleto

    Best blog ever.
    Thanks.

  • http://www.ryanpringnitz.com Ryan Pringnitz

    Great page, definitely going in my bookmarks.

  • https://renoirboulanger.com Renoir Boulanger

    Hello,

    Good article, it is sad that it publishes old fashioned methods.

    To add some positive value to my comment, I would suggest these more elegant solutions.

    1. Sanitize database inputs
    This method is very old fashioned, we have much better and builtin features for more complete filtering.

    Current PSR-X frameworks such as Symfony2 already has good filtering and also already uses PDO with transactions. Much better than using now deprecated `mysql` extension.

    Of course, if you have to do it manually, the filters and sanitizers are great!
    http://www.php.net/manual/en/filter.filters.sanitize.php

    2. Email error logs to yourself

    In symfony2 we already have this available, for free.

    http://symfony.com/doc/current/cookbook/logging/monolog_email.html

    Regarding techniques, I recommend the site http://phptherightway.com

    Hope my comment was helpful.

    (After reading, oh, people already gave some hints, good :))) ))

  • http://www.codesign2.co.uk LewisCowles1986

    Barring the distance checker, most of these do not seem like well thought out content for an article, I am sorry but sanitizing before input to sql can easily be accomplished via strip_tags($string) which has been available since PHP4 and does nothing to sanitize the data, please see http://php.net/manual/en/function.strip-tags.php

    mysqli_real_escape_string is probably your best buddy here even if you do not use mysql, as it handles sanitization of the string, although you should probably also invest in a good front-end checker too, so you can minimize the chances of a single point of failure.

    Bottom Line:
    Real PHP problems are not re-inventing core functionality, the 10 best snippets I have seen have been incredibly elegant and small, yet are so generic, they can be deployed in a series of situations, for example having a user class that takes supporting classes as pluggable objects, decoratable e-mail objects with separate business logic from content generation, it is the ability to richly, describe an application in these higher-level terms that really makes PHP such a fun language to work with transforming CURL into a REST API transport layer, or gd2 into an online diagram, building tool.

    Please focus more on teaching people how to build better vehicles rather than re-invent the wheel, especially if it will be done slowly and in a cumbersome way!

  • Derp

    Some of these snippets are really bad, especially #1. You should sanitize in a transparent way: if one writes “1 < 2", the function will turn it into "1 2", while it should be "1 < 2", for example. Also, if you only need to sanitize input for a database, you should only sanitize ' and " – which could be done by mysql_real_escape_string() alone.
    Anyway, these snippets are overall bad.

    • Derp

      It should be &lt;, sorry.

  • http://www.codegeekz.com Ceba

    Awesome list, goona use these functions and snippets for sure.

  • Robert

    The Twitter REST API v1 is no longer active. So unfortunatly, the search for a hashtag does not work anymore like this.

  • http://blog.wixiweb.fr Arnaud Lemercier (Wixiweb)

    The Twitter REST API v1 is no longer active.
    You can migrate to API v1.1.
    https://dev.twitter.com/docs/api/1.1/overview.

  • Eduardo Bustamante (dualbus)

    Deploying your own sanitizing function is a big no-no. And it’s even worse if you do it with regular expressions.

    I know that you didn’t write the code, but now you’ve given it enough visibility and people will start copy-pasting that into their projects. And, voilá, you’ll have a lot of sites vulnerable to cross-site scripting just because of that code. And the worst part is that they’re going to be thinking that they’re safe.

    Here’s a simple proof of concept to show how easy it is to break the filtering function:

    http://codepad.org/QLNNM87i

    Please take that one down, and instead suggest people to use already validated approaches, like: http://www.php.net/manual/en/function.htmlspecialchars.php

  • Ryh

    download and save remote image on your server:
    ever heard about php COPY function?
    why the hell “da snippet”?
    come on…

  • Mittul Chauhan

    i like the last tip ..

  • http://www.php-vote.com Florian

    Niceeeeeee ! :D

    Thanks for that!

  • http://www.metrixa.com Marian

    Another helpful post, definitely will try this one. Thanks for the great tips…

  • AnastisSourgoutsidis

    Instead of “Automatically create variables with the same name as the key in the POST array”, you can just extract( $_POST );

    • Benjamin Delespierre

      It’s a joke right ? Why do you think PHP disabled register_globals ? Nontheless, you still can extract(filter_input_array(INPUT_POST, $definition)) which is much more secure.

      • AnastisSourgoutsidis

        Of course you are right, however the specific snippet’s title/purpose is about creating variables, and not about sanitization. The reader should always exercise caution and not just copy-paste code from the web without understanding its use and implications.

        Having said that, if/when I ever use extract() on $_POST, I’d do it as extract(filter_input_array(INPUT_POST, $_POST), EXTR_PREFIX_ALL, ‘unique_prefix_’);
        That way I’ll be sure no existing variables are overwritten, and then I can go on with my life and sanitize the $unique_prefix_* variables that I actually need.

  • Benjamin Delespierre

    Sanitize Database Inputs >> http://php.net/manual/en/function.filter-var.php
    Create Data URI >> fetch the mime type with http://php.net/manual/fr/function.finfo-file.php
    Download & save a remote image on your server using PHP >> efficient ? maybe. safe ? absolutely not.
    Applying even/odd classes >> http://css-tricks.com/examples/nth-child-tester/
    Automatically creates variables with the same name as the key in the POST array >> you could at least isset($_POST['...']) ? $_POST['...'] : null, assigning varialbes from a superglobal can hardly be considered a snippet…

    One does not simply copy-paste random and mostly useless snippets and claim them awesome.

  • http://www.htmlguys.com/ Kevin Brylle

    Thanks for sharing this! In addition, we have also created an article regarding useful PHP functions, someone maybe interested in.