10 awesome PHP functions and snippets

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

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


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


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.


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

// 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:


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.

foreach($expected as $key){

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) {
  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'){

		foreach ($langs as $value){
			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; 
    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


    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.

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

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

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

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

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

  • Wilson Corleto

    Best blog ever.

  • Great page, definitely going in my bookmarks.

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

    2. Email error logs to yourself

    In symfony2 we already have this available, for free.


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

    Hope my comment was helpful.

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

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

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

  • The Twitter REST API v1 is no longer active.
    You can migrate to API v1.1.

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


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

  • Niceeeeeee ! 😀

    Thanks for that!

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

      • Frank Pennock

        Might make more sense to use $db->real_escape_string() instead of the filter_var().

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

  • Hi this is Rajesh i am having 3 years of experience as a php developer and i am certified. i have knowledge on OOPS concepts in php but dont know indepth. After learning Dot Net will be enough to get a good career in IT with good package? and i crossed Dot Net training in chennai website where someone please help me to identity the syllabus covers everything or not??

    thanks, Rajesh

  • Hi this is Rajesh i am having 3 years of experience as a php developer and i am certified. i have knowledge on OOPS concepts in php but dont know indepth. After learning Dot Net will be enough to get a good career in IT with good package? and i crossed Dot Net training in chennai website where someone please help me to identity the syllabus covers everything or not??

    thanks, Rajesh

  • jackson

    Your posts is really helpful for me.Thanks for your wonderful post.It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to get Dot Net Training in Chennai reach FITA.

  • jackson

    Really awesome blog. Currently I have completed Software Testing Training in Chennai at a reputed training institutes. If you are looking for best Software Testing Training Institutes in Chennai reach FITA located at Chennai, India. Rated as No.1 placement and training center in Chennai.

  • jackson

    I have read your blog. Your information is really useful for beginner. Recently I have completed Software Testing Course in Chennai at a reputed institutes.Its really useful for me to make a bright carrer. If anyone want to get Manual Testing Training in Chennai reach FITA.

  • Software testing industry offer
    huge career opportunity for talented professionals. software
    testing training in Chennai

  • Excellent post!!! Selenium automation testing tool makes
    your software validation process lot simpler. Keep on updating your blog with
    such awesome information. Selenium
    Course in Chennai

  • Thanks for your informative article on UFT automation testing tool.
    Your post helped me to understand the features and functionality of QTP
    automation testing tool. QTP training
    institute in Chennai

  • hi, in this blogs posts is very awesome.hadoop training in chennai.It’s clearly explain lot of my confusion.oracle training in chennai..Thanks a lot..oracle dba training in chennai..

  • Hi,i have to clearly learning very best information.hadoop training in chennai..you have to sharing now lot of information.oracle training in chennai..thank you so much.oracle dba trainig in chennai..

  • Nancy Rani

    I have joined the oracle Trained in Training in Bangalore. Oracle Trainer will be teaching in practically Manner. So I can Easily able to understand the any Concept. This is very helpful for the interviews Purpose . I would refer my frnds to joined this institute. Visit Us, Oracle Training in Bangalore

  • Nancy Rani

    Thanks for sharing this Information blog. Recently I have completed Oracle Training Courses in Bangalore at a leading Company. It’s really useful for me to make a bright Future career. Visit Us, Oracle Training in Bangalore

  • Guest


  • gokul vijay

    They are offer the best hadoop training for students.This training is very useful for you career.I have read you article very useful information hadoop taining. Thank you for sharing you article.Hadoop Courses in Chennai

  • Thanks for sharing, very nice and informative

    study in singapore from India

  • Thank you admin for sharing such informative article on mobile
    testing training in Chennai

  • Fully Help

    Great beginning php tutorials Very clear and helpful for beginners. Great job you did here Thank you so much, this is what I looking for a long time.

  • Online girls chat rooms join for free no registration needed 🙂
    Chat Rooms
    Asian girls chat rooms

  • Thanks for sharing this information.


  • lucy

    Thanks for your PHP function and the syntax. I am understand the functions and snippet.

  • lucy

    Thanks for sharing your Php syntax with us.I learned it. It was very interesting to read and also improving our developing skills.easy functions are followed to study the php concepts.this is the server side scripting language designed for web development.

    To get more ideas on PHP visit our link for a while:


  • Jaishri Ramsmo

    Arrange some interesting story guides, covering guides, questions, games, etc. http://bit.ly/1vaWKnT These products will keep your children busy on the moving day or a lengthy drive.

  • sindhu Khan

    This php functions are very useful.Thanks for this information.we also provide the
    authorized training in our institute.It offers excellent jobs and more benefits.

  • Jenilia Mohan

    wonderful article about PHP syntax with its script. keep update. we need more information.

  • Manikanta Sandeep

    If you must limit Firefox on Ubuntu 12.04, this reply explains how to go back to Opera 20. A more basic explanation of a way to switch to any version of Opera is offered here. Then use this response to set Firefox upgrades on hold till Selenium releases an update that works together with the later version of Firefox.

  • Mahesh Bayyarapu

    JQuery And KendoUI Date
    Picker Schedule instance

    In this guide, we will have how exactly to use Day
    Picker by getting unique calendars. We shall consider three unique calendars
    and find out how exactly to use them. You can find different time pickers found
    in purposes case JQuery date picker, KendoUI day picker etc
    . For more info on this visit this link

  • Thanks for sharing informative article

  • Sweekruthi Jagarlamudi

    Excellently written article,You put really very helpful information.Thanks for sharing us a great information that is actually helpful for my blog http://www.happydiwalismsmessages.in/

  • Pinky DreamGirl

    Nice post buddy You can also check

    Merry Christmas SMS Quotes http://www.merrychristmassmsquotes.net/

  • kelly grace

    Great information for every PHP developers. Still, They can improve their knowledge from here. I welcome your efforts. training for it software courses

  • Pinky DreamGirl

    Nice Post Buddy http://hitorflop.net/

  • Nice post.
    BTW, You guy can test the above code here: phpio.net

  • Jone Sathya

    Thanks for the useful information, I been searching for this kind of example for pretty long time indeed. The santize data base inputs are clearly explained. know more about PHP Training here..

  • Here is a good resource if anyone in need of asp.net web development services
    Hire asp .net programmers