Use your left/right keys to browse tutorials
6 Useful PHP code snippets

6 Useful PHP code snippets

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on February 6, 2012

Here’s a selection of really useful PHP code snippets that I find using on a weekly basis. You could use these as is or expand them as part of other applications or add them to a php class.

Adjust server time

If you have a server in a different timezone to you then you might be seeing funny things happen when you add the time to a MySQL database for example. You can fix this by adding or subtracting hours as in the example below.


$now = date('Y-m-d-G');
$now = strftime("%Y-%m-%d-%H", strtotime("$now -8 hours"));

Create a slug URL from string of text

Here we’re passing in a simple string of text converting it to lowercase and replacing all the spaces with a dash.


function create_slug(strtolower($string)){
   $slug=preg_replace('/[^a-z0-9-]+/', '-', $string);
   return $slug;
}

echo create_slug('Create a slug URL from string of text');

Convert HEX value to RBG

If you’ve ever need to get an RGB colour format converted from a Hexadecimal this is the function for the job.


function hextorgb($hexvalue){
        if($hexvalue[0] == '#') {
                $hexvalue = substr( $hexvalue, 1);
        }
        if(strlen( $hexvalue ) == 6){
                list($r, $g, $b) = array($hexvalue[0] . $hexvalue[1], $hexvalue[2] . $hexvalue[3], $hexvalue[4] . $hexvalue[5]);
        }elseif (strlen($hexvalue) == 3) {
                list($r,$g,$b) = array($hexvalue[0] . $hexvalue[0], $hexvalue[1] . $hexvalue[1], $hexvalue[2] . $hexvalue[2]);
        }else{
                return false;
        }
        $r = hexdec($r);
        $g = hexdec($g);
        $b = hexdec($b);
        return array('R' => $r, 'G' => $g, 'B' => $b);
}


$rgb = hextorgb('#fff000');

print_r($rgb);

Display a users Gravatar image

Getting users images from Gravatar is simple. If you have the users email address you just need to MD5 hash it and append it to the gravatar URL.

   $gravatar = 'http://www.gravatar.com/avatar/' . md5($email_address) . '?s=32';
   echo '<img src="' . $gravatar . '" width="32" height="32"/>';

Convert links in a string of text to hyperlinks

Very useful function which will convert a string of text and ad hyperlinks to all the URLs. We loop through each URL and add a hyperlink


function url_to_link($text){
           
            $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
            // Check if there is a url in the string
            if (preg_match_all($reg_exUrl, $text, $url)) {
                
                foreach($url[0] as $v){
                   
                    $position = strpos($text,' '.$v)+1;    
                    $text = substr_replace($text,'', $position, strlen($v));
                    $text = substr_replace($text,''.$v.'', $position ,0);
                }
                return $text;
            }
            else {
                // if no urls in the text just return the text
                return $text;
            }
        }

$string = 'This is a string of text and we have a link: http://papermashup.com we also have another link http://google.com';
echo url_to_link($string);

Parse JSON in PHP

Parsing a string of JSON is easier than you may think as we can use the json_decode() function in PHP which will convert the JSON into an array in PHP which we can then manipulate as needed.


  $json ='{"id":0,"name":"Ashley","surname":"Ford","Website":"http://papermashup.com"} ';

   $array=json_decode($json);
   
   // print  the array
   print_r($array);
   echo $array->name; 



More tutorials from Papermashup
Comments
8 discussions around 6 Useful PHP code snippets
  1. Voyagewave says:

    Setting up server time is useful snippet and json decoding one too. thanks

  2. sonu sindhu says:

    unreliable script nice work
    Thanks for many many help for this..

  3. saha says:

    Very useful code snippets. I’ll use adjust server time code and code Display a users Gravatar image. Thanks for sharing these code snippets.

  4. phphunger says:

    i will add these to my library…great work….

  5. Brian says:

    Awesome post. Would be usful to see snipit #2 in JavaScript form. :)

  6. rmmoul says:

    As always, good stuff.

    That function for finding links is going into my tool box!

  7. Chris says:

    Nice snippets for beginners. It is worth to mention what slug function is not UTF-8 compliant, and with some characters(chinese, cyrillic, latin extended) it will skip letters.

  8. Jeremy says:

    Thank you!! You have just made my day!! I will definetly be using at least 4 of these by the end of the day!!





Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.