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!

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


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


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

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


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. The two lines of code below will do it for you.

$image = file_get_contents('');
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

	$page_id = "302807633129400";
	$xml = @simplexml_load_file("".$page_id."") or die ("a lot");
	$fans = $xml->page->fan_count;
	echo $fans;

Source: WPRecipes

  • lahaxe_arnaud

    ereg_replace is deprecated since PHP 5.3.0 (end of support in 2014)

    • You’re totally right. The related snippet has been removed and will be replaced.

  • Michael Ramsey

    The meta keywords tag is essentially deprecated. It serves no purpose in terms of SEO. Some people still use it as a way of remembering what they optimized the page for, but it’s becoming less and less common to see it implemented, let alone correctly filled out.

    Most sites that I’ve worked on in recent years that have meta keywords filled have not included the actually relevant terms on a page-by-page basis.