PHP Ping Script Video Tutorial

Webucator, a provider of online and onsite business and technical training, contacted me and asked if they use my php ping script article as a basis for a new training video. The video would be added to their list of PHP courses. I allowed them to use the php ping script as part of their video and a few days later I was sent a link to the newly created php ping script video.

After watching the video Webucator created, I was was truly amazed and it had surpassed all my expectations. Webucator have managed to perfectly convert the written article into an easy to understand, fully comprehensive and simple to follow php tutorial video.

I was impressed with how much detail the above php video tutorial encompassed. The video covers each of the different php ping scripts, and perfectly explains how each of the php ping scripts work. They also highlighted the strengths and usefulness of the each script as well as demonstration a working version of each script.

The video also pays attention to vital parts of each script, such as:

  • Why you should escape arguments passed to the ping script.
  • The situations in which each ping script is most useful.
  • Which ping script you should be using if the website is blocking icmp packets.

Take a look at the video and check out their other training videos. It will be well worth your time.

PHP Get File Extension Quickly


If you are looking for the quickest way to check a file extension in PHP, then you have reached the best article to read. Perhaps you need to get file extension in PHP of a file that has been uploaded or use php to check a file extension of an existing file on your website. In any case, the below function will show you how to do it in the least amount of code.

PHP Get File Extension Quickly


$filename = "/home/darian/";

// get the php file type
$extension = pathinfo($filename, PATHINFO_EXTENSION);

// display the extension: This will echo out ".jpeg"
echo $extension;


How Does The Above Code Work

We use the php function pathinfo() which will take a path (such as “/home/darian/” in our example) and will return the information about that full path. For example, if we had to run the following code:

$path_info = pathinfo($filename);

It would output an array with information similar to this below

    [dirname] => /home/darian
    [basename] =>
    [extension] => jpeg
    [filename] =>

As you can see, the element extension contains the file extension. Now we can speed this function up even further by adding the flag PATHINFO_EXTENSION which tells the function to only return the file extension as a string rather than an array with all the additional information.

Quickest Way To Remove Empty Array Elements PHP


Here I will show you the quickest way to remove empty values from an array.
The first way is slow but the most logical way of approaching this. Luckily the second example is the quickest and also pretty simple way. Use the second way, trust me, you will love it.

The slow but simple way – don’t use

Here is the most straight forward way of doing this. It works but I will show you a quicker way afterwards.


// our massive array with set values and empty values
$array = array(...);

foreach( $array as $key => $value )
	if( $value == "" ) unset($array[$key]);


Quickest Way To Remove Empty Array Elements PHP

And here is the quickest way I have found to remove empty array elements php. Below we fetch a list of keys from the array that is empty (using the php function array_keys) and then unset each of those values.


// our massive array with set values and empty values
$array = array(...);

// get the empty array keys using array_keys
$keys = array_keys($array,"");

// foreach empty key, we unset that entry
foreach ($keys as $k)


Simple yet surprisingly quick.

CSS Button Sprite Example

What IS A CSS Button Sprite?

Let me start off by explaining what an image sprite is. A sprite is basically one larger image that is made up of many smaller images. The idea of sprites is that you only need to load one image and then apply it to a smaller div or A tag so only a portion of the large image shows. Then depending on the background position of the image, you will only see one of the smaller images. This tutorial will be useful if you want to create button sprites, menu sprites, sprite animations or any other type of sprites.
If you would like to see an example on using these sprites to create a sprite animation, check out the sprite animation tutorial.

CSS Button Sprite Example

Below is showing you a css button sprite. This article will show you how to create this button sprite.

Above is the finished example of what this tutorial will show you. Mouse over this sprite button image and see how it works and bear in mind that we are only using one image to create the rollover effect. The button is actually an A (anchor) tag that has a height 32px which is half of the image sprite height. This way, only the top half of the image shows which is the up state part of the image.

Why should you use css sprites?

Before images and css items can be displayed on your webpage, your browser must request the item such as javascript files, images, css files, etc. Each request takes time and your browser must wait for a response and then download the file for it to be displayed. So in short, the less items means less time to request and download items, meaning less time to load a page. So using sprites will increase the speed at which your website loads.

Button Sprite

Button Sprite

Above is the css button sprite image I made to create the above button sprite with it’s two states. Normal state when it is untouched and second state is the hover state for when we mouse over it. Notice that the one image contains both up and down states and then as we mouse over it, we use css to adjust the background position of the image sprite to make it appear that the button state is changing.

Now for the code to get this all working

CSS Code

/* css to style the button */
#rollover {
	background: #FFF url("images/sprite.png");
	width: 180px;
	height: 32px;
	display: block; /* can use inline-block instead of block */
/* hover is trigger when we mouse over the A (anchor) tag and adjust the
	background position of the sprite to make it appear the button is down */
#rollover:hover {
	background-position: 0 -32px;


Next the html A (anchor) tag we apply the rollover button style to.

<a href="#-" id="rollover"> </a>

Now when we mouse over, it will appear that the button is changing states. Image sprites aren’t only for buttons, but can be used for rollover menus, animations, or anything that has multiple display states.

PHP Header Force Download Of Files


In apache, the file type will usually determine how the file is handled. It can opened and displayed in the browser or download, etc. For example, images, css, javascript, php, html (and other types) files are executed and displayed within the browser whereas PDF, ZIP, EXE and other unknown file types will be downloaded by the browser. Usually this behaviour is suitable however we may want to change how certain file types are handled and then force an Image or PHP script file to be downloaded.

PHP Header Force Download Of Files

The below PHP Header code will force any file to be downloaded rather than just being displayed in a browser. You can use this code to force PDF download or to force an Image to download or force download of a javascript file rather than having these file types displayed or executed by the browser.

PHP Header Code To Force File Download


/* The name of the file we want to force a download */
$filename = 'somefile.html';

/* set our content type to match the file we are downloading */
header("Content-Type: text/html");
/* Tell the browser how big the file is going to be */
header("Content-Length: ".filesize($filename)."\n\n");
/* force the file to be downloaded */
header("Content-Disposition: attachment; filename=$filename");

/* echo out the contents of the file */
echo file_get_contents($filename);

Important Note

Remember that since we are sending headers, we need to make sure that there is no output sent to the browser before the headers are sent. Also, the file mime type should match the file type, such as a mime-type of image/png for PNG files and application/pdf to force a PDF file to download.

Note that you can force the download to have a different name by changing the filename for the Content-Disposition header to the filename of your choice.
For a more complete list of file mime-types, you should visit my article on list of file mime-types. If you would like to learn to to determine the mime-type based on the file extensions, check out this article.

Common List Of Mime Types

Below is a list of mime types I come across most often. Suggest others mime-types that should be a part of the list by leaving a comment below. You can also view my other article on finding the mime-type of a file to see how you can return the mime-type of a file determined by the file extension.

List Of Mime Types


PHP – text/html
HTML – text/html
HTM – text/html
CSS – text/css


– multipart/mixed


PDF – application/pdf
ZIP – application/zip
JAVASCRIPT – application/javascript
JSON – application/json


GIF – image/gif
JPEG – image/jpg
JPG – image/jpg
PNG – image/png


MPEG-1 – video/mpeg
MP4 Video – video/mp4
Quicktime – video/quicktime
WMV – video/x-ms-wmv
3GP – video/3gpp


MP3 – audio/mpeg
MP4 – audio/mp4
Ogg Vorbis – audio/ogg

If you see anything missing from my list of mime types, please message me or leave a comment.


Browsers will detect the mime-type of files and display them accordingly. And because of this, it is important to have the correct Content-Type header set for your files. For example, if you read a jpeg from disk and echo the contents to the page, you must set the content type to image/jpeg or image/png in order for the browser to display it as an image and not just display the contents of the file.

Fastest Way To Format File Size In PHP


In this short post, you will find a PHP function that has got to be the quickest way to convert bytes into an easier to read format of kilobytes, megabytes, gigabytes and petabytes. The PHP filesize convert function below takes the number (as bytes) passed to it and will convert it into an easier to read format. It will also round off the result to 2 decimal places. Very convenient and free from my site.

Fastest Way To Format File Size In PHP

The PHP convert function will take the number passed to it and continually loop and divide the number by 1024. We divide by 1024 since that is the number of bytes in a kilobyte as well as the number of kilobytes in a megabyte and so on. Each time we divide by 1024, we see if the result is still bigger than 1024. Once the number is less than 1024, we then count the number of times we had to divide the original number and that will tell us if the number is B, KB, MB, etc. For example, if we divided the number 3 times, that would mean the original number is in the GB. So we get the third element out of our $types array which returns GB.


function formatSize( $bytes )
	$types = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
	for( $i = 0; $bytes >= 1024 && $i < ( count( $types ) -1 ); $bytes /= 1024, $i++ );
		return( round( $bytes, 2 ) . " " . $types[$i] );

Usage Examples

Below are some examples on how to format file size in php using the above function.


// call the above formatSize function and pass it a number as bytes

echo formatSize(8763432); // will echo 8.35 MB
echo formatSize(258); // will echo 258 B
echo formatSize( filesize('/path/to/some/file'); // will echo out the file size of that file


Output Json Header In PHP

Overview of JSON

JSON is an acronym for JavaScript Object Notation. It is essentially a way of exchanging data between a source and destination using name/value pairs. Commonly used when transferring data from a database to a website using AJAX.

Generating a JSON object using php is pretty simple (although it won’t be covered in this article), the lesser known technique is setting the correct content type so that the php page that generates the JSON object is seen as an actual JSON object rather than a plain text/html page.

Some libraries such as jQuery.getJSON() will detect wether or not the html page is a json response by looking at the Content-Type header of the response.

Json Content Type

What I mean by the correct content type is that each file type has its own content type which tell the browser how to handle the file. It informs the browser of what type of file follows so the browser is more aware on how to handle the content. For example a css file is seen as text/css where as an html or php file is seen as a text/html and likewise an image file can be image/jpg or image/png.

For a complete list of mime-types view this article or if you want to learn how to determine a mime-type of a file, click here.

Output Json Header In PHP

As for JSON, it can be output as a javascript file but also output as a json file. To overwrite the default content of text/html that the php file will most likely be, we will set the correct headers using php’s header(); function as you can see below.

Output as Json Using PHP Headers


// set our content-type to json
//  note that a Content-type of application/javascript works just as well as application/json
header('Content-Type: application/json');

// now output our json object
echo '{"name":"darian","lastname":"brown","age":87,"adress":{"21 somewhere street","my city","Australia"}}';


Now when the page is loaded, the page will be seen as a JSON script rather than a simple html page.

Convert PHP Array to JSON Object

It is very easy to convert a php array into a json object using the php function json_encode(). It simply takes a multidimensional php array and converts it into a valid json string that will be read as a json object by javascript.


// create our php array - this will convert to a json object
$array = array(
	"name" => "darian",
	"lastname" => "brown",
	"age" => 87,
	"address" => array(
		"21 somewhere street",
		"my city",

// now we convert the above array to json string using json_encode()
$json = json_encode($array);

// set the json header content-type
header('Content-Type: application/json');
// and output the $json string so that it can be handled by our javascript code as a json object
echo $json;

// above echo will output our array as
//	'{"name":"darian","lastname":"brown","age":87,"adress":{"21 somewhere street","my city","Australia"}}'


Calculate Time Difference Between Your End User And Your Server


People access your site aren’t always in the same timezone as you are. Now perhaps you would like to determine what the time is for a user in a different country. Then here is a quick way to find this information out.

This example is very useful if you simply want to fetch your clients date and time or timezone; but also good to see what time of day (their time, not server time) your clients access your website.

Now before I should you the code, remember that PHP is server side code – ie. it runs on the server and as such doesn’t have access to the clients local time. Javascript however is client side code which means it can see the localtime but the servers time. So a combination of the two will allow us to calculate the difference.

How To Calculate Time Difference

The way the below example works, is that the client will click a submit button which sets the value of the hidden input field to their local time stamp and that gets submitted to the same php script. Then the php script checks if that value has been sent and if it has, then it gets the local time (of the server) and takes the clients times and shows a message depicting the difference.

<!DOCTYPE html>
	<title>Server and Client Time Example</title>
	<script type='text/javascript'>

	// when we submit the form, get the client time and submit it as the
	// hidden field 'client_timestamp'
	function getClientTime() {
		var d = new Date();
		// we divide the timestamp by 1000 to go from milliseconds to seconds
		var timestamp = Math.floor(d.getTime()/1000);

		// put the timestamp into hidden field to be passed with the form
		document.getElementById('client_timestamp').value = timestamp;


	<form method='post' id='myform' onsubmit='getClientTime();'>
		<input type='hidden' id='client_timestamp' name='client_timestamp' />
		<button type='submit'>Send My Time</button>


	// if the form with the timestamp was submitted
	if( isset( $_REQUEST['client_timestamp'] ) ) {
		// the time posted to this script through the form
		$client_time = $_REQUEST['client_timestamp'];

		$server_time = time();

		$client_string = 'Your clients time is: ';
		$client_string .= date('d F Y h:i:s A',$client_time);

		$server_string = 'Your server time is: '
		$server_client .= date('d F Y h:i:s A',$server_time);

		// display the times
		echo $client_string.'<br />';
		echo $server_string.'<br />';




Why Unix Timestamp Is Useful


Unix timestamps are a way or storing a specific date and time. Unix timestamps are a 10 digit number that represents the number of seconds that have passed since midnight Universal Co-ordinated Time (UTC) of January 1st, 1970.

What makes timestamps ever so useful is that since timestamps are recorded as of UTC (or GMT) a single time stamp can be used to to represent all time zones. Once you have your timezone, the unixtime stamp will adjust the time accordingly. For example, a unix timestamp of 1304951846 can represent 10th May at 0:37 AM in London, but it would also represent 10th May at 10:37 AM in Brisbane/Australia.

Why Unix Timestamp Is Useful

How can this be useful? Just think, users can see dates and times on your website relative to their own timezone, rather than the timezone of the server the website is being run on. Being a web developer, I am forever finding myself storing dates do be displayed back to the user. It may be a date a user last logged into a program or website, perhaps even a date that a user posted an article such as this to a website. Once we store a specific timestamp, we can display the time and date to users but also in the correct relevant timezone. On top of which, timestamps are easy to use, and many languages support them.

Online Timestamp Converter

There are online unix timestamp generators to convert to and from unix time stamps such as the one found here.

PHP can convert a timestamp to a human readable format by using the date() function and likewise using strtotime() and mktime() to convert a natural language string to a unixtime stamp to be stored. Short examples are:

PHP Timestamp Example


/* convert unixtime stamp to human time */
echo date('d F Y H:i:a',1304951846); // would display a time of 10 May 2011 00:37:am

/* convert to a unix time stamp */
echo strtotime('+1 Year'); // would return the timestamp of 1 year from today
echo mktime($hour,$min,$sec,$month,$day,$year); // echo a timestamp specified by the variables


MySQL Timestamp Example

MySQL uses the syntax FROM_UNIXTIME to convert data to a human readable format for example:

SELECT *,FROM_UNIXTIME(timestamp_column) FROM `table`;

Free Online Unix Timestamp Converter

Generate your own unix timestamp online using an Online Unix Timestamp generator.