11 Useful Code Snippets for PHP Developers

As a PHP developer, it is very useful to keep code snippets in a personal library for future use. These code snippets can save your precious time and also increase your productivity.

Here is a list of some useful PHP code snippets that I have added to my personal PHP code library during working on PHP projects. These code snippets are collected from useful PHP tutorial websites. If you have any code snippet and think to be useful for other, you can share it through comment section.

Also, read:

 

Generate CSV file from a PHP array

It’s really a very simple function to generate a .csv file from a PHP array. This function uses fputcsv PHP built-in function for generating comma separated file (.csv). The function takes 3 parameters: data, delimiter and the csv enclosure which is double quote by default.


function generateCsv($data, $delimiter = ',', $enclosure = '"') {
   $handle = fopen('php://temp', 'r+');
   foreach ($data as $line) {
		   fputcsv($handle, $line, $delimiter, $enclosure);
   }
   rewind($handle);
   while (!feof($handle)) {
		   $contents .= fread($handle, 8192);
   }
   fclose($handle);
   return $contents;
}

Source taken from:http://snipplr.com/view/66856/generate-csv-file-from-array-using-php/

Sanitize Database Inputs using PHP

This is a useful PHP function which sanitizes all input data and removes the chances of code injection.

function sanitize_input_data($input_data) {
	$input_data = trim(htmlentities(strip_tags($input_data,“,”)));
	if (get_magic_quotes_gpc())
	$input_data = stripslashes($input_data);
	$input_data = mysql_real_escape_string($input_data);
	return $input_data;
}

Source taken from:https://www.phpzag.com/sanitize-database-inputs-in-php/

Unzip files using PHP

This is a very handy PHP function to unzip file from .zip file. It takes two parameters: first is .zip file path and second is destination file path.

function unzip_file($file, $destination) {
	// create object
	$zip = new ZipArchive() ;
	// open archive
	if ($zip->open($file) !== TRUE) {
		die ('Could not open archive');
	}
	// extract contents to destination directory
	$zip->extractTo($destination);
	// close archive
	$zip->close();
	echo 'Archive extracted to directory';
}

Source taken from:http://www.catswhocode.com/blog/snippets/unzip-zip-files


Extract keywords from a webpage

Really a very useful code snippet for extracting 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 taken from:http://www.emoticode.net/php/extract-keywords-from-any-webpage.html

Check if server is HTTPS

This PHP snippet give you exact information about your server SSL enable(HTTPS).

if ($_SERVER['HTTPS'] != "on") { 
	echo "This is not HTTPS";
}else{
	echo "This is HTTPS";
}

Source taken from:http://snipplr.com/view/62373/check-if-url-is-https-in-php/

Display source code of any webpage

This is simple PHP code to display source code of any webpage with line numbering.


$lines = file('http://google.com/');
foreach ($lines as $line_num => $line) { 
	// loop thru each line and prepend line numbers
	echo "Line #{$line_num} : " . htmlspecialchars($line) . "
\n";
}

Source taken from:http://perishablepress.com/code-snippets/#code-snippets_php

Create data URI

As we know that data URI can be useful for embedding images into HTML, CSS and JS to save on HTTP requests. This is a very useful PHP code snippet to create data URI.

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

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

Find All Links on a Single Page

By using this code snippet, you can easily get all links from any webpage.

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

$dom = new DOMDocument();
@$dom->loadHTML($html);

// 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.'
';
}

Source taken from:http://snipplr.com/view/70489/find-all-links-on-a-page/


Make page titles seo-friendly for URL

This is useful PHP function to create search engine friendly URLs based on page titles.

function make_seo_name($title) {
	return preg_replace('/[^a-z0-9_-]/i', '', strtolower(str_replace(' ', '-', trim($title))));
}

Source taken from:http://snipplr.com/view/7866/make-page-titles-seofriendly-for-url/

Just Download & save a remote image on your server using PHP

If you want to download images from a particular URL and save them on your server then this code snippet worked you.

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

Source taken from:http://www.catswhocode.com/blog/snippets/download-save-a-remote-image-on-your-server-using-php

Display Facebook fans count in full text

This is very handy code snippet if you want to display the number of Facebook fans on your blog. It’s very easy using just pass the facebook profile name.


function fb_fan_count($facebook_name){
    $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
    echo $data->likes;
}

Source taken from:http://www.digimantra.com/

You may also like: