Super Useful PHP Snippets

DZone 's Guide to

Super Useful PHP Snippets

When developing websites, apps, or blogs, code snippets can be a real time saver. Today, I’m sharing super useful PHP snippets that I’ve collected over the past months. Enjoy!

· Web Dev Zone ·
Free Resource
When developing websites, apps, or blogs, code snippets can be a real time saver. Today, I’m sharing super useful PHP snippets that I’ve collected over the past months. Enjoy!

Create Data URI’s

Data URI’s can be useful for embedding images into HTML/CSS/JS to save on HTTP requests and consequently enhance your site loading time. The following function will create a Data URI based on $file for easier embedding.

function data_uri($file, $mime) {
 echo "data:$mime;base64,$base64";

Source: CSS Tricks

Combine JavaScript and CSS files

Another good tip to minimize HTTP requests and save on page loading time: combine your CSS and JS files. While I would recommend using a dedicated plugin to do so (such as minify), it’s still very easy to combine files using PHP. Let’s have a look:

function combine_my_files($array_files, $destination_dir, $dest_file_name){

 if(!is_file($destination_dir . $dest_file_name)){ //continue only if file doesn't exist
 $content = "";
 foreach ($array_files as $file){ //loop through array list
 $content .= file_get_contents($file); //read each file

 //You can use some sort of minifier here

 $new_file = fopen($destination_dir . $dest_file_name, "w" ); //open file for writing
 fwrite($new_file , $content); //write to destination
 return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combined file
 //use stored file
 return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combine file

And, the usage would go like this:

$files = array(

echo combine_my_files($files, 'minified_files/', md5("my_mini_file").".js");

Source: Sanwebe

Find Out if Your Email Has Been Read

When sending emails, you might want to be able to find out if your email has been read. Here’s a very interesting snippet which logs the IP address which read your email, as well as the actual date and time.

Header("Content-Type: image/jpeg");

//Get IP
if (!empty($_SERVER['HTTP_CLIENT_IP']))
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))

$actual_time = time();
$actual_day = date('Y.m.d', $actual_time);
$actual_day_chart = date('d/m/y', $actual_time);
$actual_hour = date('H:i:s', $actual_time);

//GET Browser
$browser = $_SERVER['HTTP_USER_AGENT'];

$myFile = "log.txt";
$fh = fopen($myFile, 'a+');
$stringData = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . "\r\n";
fwrite($fh, $stringData);

//Generate Image (Es. dimesion is 1x1)
$newimage = ImageCreate(1,1);
$grigio = ImageColorAllocate($newimage,255,255,255);


Source: emoticode.net

Extract Keywords from a Webpage

The title said it all: a great code snippet to extract easily meta keywords from any webpage.

$meta = get_meta_tags('http://www.emoticode.net/');
$keywords = $meta['keywords'];
// Split keywords
$keywords = explode(',', $keywords );
// Trim them
$keywords = array_map( 'trim', $keywords );
// Remove empty values
$keywords = array_filter( $keywords );

print_r( $keywords );

Source: emoticode.net

Find All Links on a Page

Using the DOM, you can easily grab all links from any webpage. Here’s a working example:

$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
 $href = $hrefs->item($i);
 $url = $href->getAttribute('href');
 echo $url.'<br />';

Source: Snipplr

Auto-convert URL into Clickable Hyperlink

In WordPress, if you want to auto convert all URLs in your string into clickable hyperlinks, you can actually do it using the built-in function make_clickable(). If you need to do that outside of WordPress, you can refer to the function’s source code at wp-includes/formatting.php:

function _make_url_clickable_cb($matches) {
$ret = '';
$url = $matches[2];

if ( empty($url) )
return $matches[0];
// removed trailing [.,;:] from URL
if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;

function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;

if ( empty($dest) )
return $matches[0];
// removed trailing [,;:] from URL
if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;

function _make_email_clickable_cb($matches) {
$email = $matches[2] . '@' . $matches[3];
return $matches[1] . "<a href=\"mailto:$email\">$email</a>";

function make_clickable($ret) {
$ret = ' ' . $ret;
// in testing, using arrays here was found to be faster
$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);

// this one is not in an array because we need it to run last, for cleanup of accidental links within links
$ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
$ret = trim($ret);
return $ret;

Source: zenverse.net

Download & Save a Remote Image on Your Server

Downloading an image on a remote server and saving it on your own server is useful when building websites, and it’s also very easy to do. These two lines of code below will do it for you.

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

Source: Cats who code

Detect Browser Language

If your website is multilingual, it can be useful to detect the browser language to use this language as the default. The code below will return the language used by the client’s browser.

function get_client_language($availableLanguages, $default='en'){

foreach ($langs as $value){
if(in_array($choice, $availableLanguages)){
return $choice;
return $default;

Source: Snipplr

Display Number of Facebook Fans in Full Text

If you have a Facebook page for your website or blog, you might want to display how many fans you have. This snippet will help you to get your Facebook fan count, in full text. Don’t forget to add your page ID on line 2. Your page ID can be found at the address http://facebook.com/yourpagename/info.

$page_id = "302807633129400";
$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
echo $fans;

Source: WPRecipes 

php, snippets, web developement

Published at DZone with permission of Jean-Baptiste Jung , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}