10 super useful PHP snippets

Posted on Apr 03, 2011

Having the right code snippet at the right time can definitely be a life saver for web developers. Today, I've compiled 10 really awesome PHP code snippets that will, I hope, be very helpful in your forthcomming developments.

Super simple page caching

When your project isn’t based on a CMS or framework, it can be a good idea to implement a simple caching system on your pages. The following code snippet is very simple, but works well for small websites.

<?php
// define the path and name of cached file
$cachefile = 'cached-files/'.date('M-d-Y').'.php';
// define how long we want to keep the file in seconds. I set mine to 5 hours.
$cachetime = 18000;
// Check if the cached file is still fresh. If it is, serve it up and exit.
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
include($cachefile);
exit;
}
// if there is either no file OR the file to too old, render the page and capture the HTML.
ob_start();
?>
<html>
output all your html here.
</html>
<?php
// We're done! Save the cached content to a file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
// finally send browser output
ob_end_flush();
?>

Basic PHP whois

Whois services are extremely useful to get basic information about a domain name: owner, creation date, registrar, etc. Using PHP and the whois unix command, it is extremely easy to create a basic whois PHP function. Please note that the whois unix command must be installed on your server for this code to work.

Get latitude and longitude from an adress

With the popularity of the Google Maps API, developers often needs to get the latitude and longitude of a particular place. This very useful function takes an adress as a parameter, and will return an array of data containing both latitude and longitude.