PHP

PHP

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

Overview

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

<?php

$filename = "/home/darian/any.file.name.jpeg";

// 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/any.file.name.jpeg” 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

Array
(
    [dirname] => /home/darian
    [basename] => any.file.name.jpeg
    [extension] => jpeg
    [filename] => any.file.name
)

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

Overview

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.

<?php

// 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.

<?php

// 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)
	unset($array[$k]);

?>

Simple yet surprisingly quick.

PHP Header Force Download Of Files

Overview

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

<?php

/* 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.

Fastest Way To Format File Size In PHP

Overview

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.

<?php

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.

<?php

// 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 http://www.json.org/ 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

<?php

// 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.

<?php

// 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",
		"Australia"
	)
);

// 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

Overview

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>
<html>
<head>
	<title>Server and Client Time Example</title>
</head>
<body>
	<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;
	}

	</script>

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

	<?php

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

	?>

</body>

</html>

Why Unix Timestamp Is Useful

Overview

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

<?php

/* 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.

Running PHP Script From Cron

Overview

Cron is a job based scheduler used in Unix type operating systems. It allows you to schedule tasks to be run at given intervals such as scheduling a php script to run weekly, every second day, hourly, every 3 minutes, weekends, and so on.
In this article, I will show how easy it is in running a php script from cron. It will also show you how you can run a php script via a url using wget.

Running PHP Script From Cron

I will show you 3 ways on running php script from cron which are:

  1. Running php script via command line in cron
  2. Running php script via php5-cgi in cron
  3. Running php script remotely via website url in cron

Running a php script usually requires the php script to have execute permissions set. Running PHP script from cron is usually a matter of specifying the file and as long as the script has execute permissions (i.e. chmod +x) then all should be good. Here are three ways I have found work very well.

Running PHP Script On Command Line From Cron

In order for the script to run correctly you should add the following to your php script. The informs the bash what type of script it is executing.

#!/usr/bin/php
<?php

//.. your code follows here

Next we add the entry into cron.

# you could output to a file by changing /dev/null to /some/file/to/save.log
*/10 * * * * /home/user/scripts/updatesomething.php > /dev/null

Note we didn’t need to execute the script via php (/usr/bin/php /path/to/script.php) since we added the header to the php script.

Running php script via php5-cgi in cron

To execute the php script from cron you need to have php5-cgi installed. You can install this on Debian use “apt-get install php5-cgi” or the equivalent command for your distribution of linux.

# PHP5-CGI: execute the php script every 2 minutes and send output to /dev/null
# you could output to a file by changing /dev/null to /some/file/to/save.txt
*/2* * * * php5-cgi -q /home/user/scripts/parselogs.php > /dev/null

Running php script via website url in cron

And lastly we will use wget from the cron to download a website url and thus, execute the url that the php script is located at. We do this in the cron to allow the url to be downloaded at set times. To use wget, you need to install it wget using “apt-get install wget” or the equivalent command for your distribution of linux.

# wget will visit the url but won't save the file. send it to /dev/null
# this executes the script as if you visited the link in your browser
0 * * * * wget -O /dev/null http://www.example.com/some_cron_script.php

And there we go, your php script will be run by cron on time, every time.

PHP Get Mime Type From File Extension

Overview

Whenever you need to determine the mime-type of a file you should generally look at the file extension. Below is a pretty straight forward function that will return the mime-type of a file based on its file extension. Note! this is not a guaranteed way to determine the mime-type since people can easily fake the file extension. All you need to do is pass the php mime function a filename and it will try figure out what the mime type is.

PHP Get Mime Type From File Extension

Here is the function to retrieve the mime type of a file based on the file extension. See here for a list of mime-types.

<?php

function get_mime_type($file)
{

	// our list of mime types
	$mime_types = array(
		"pdf"=>"application/pdf"
		,"exe"=>"application/octet-stream"
		,"zip"=>"application/zip"
		,"docx"=>"application/msword"
		,"doc"=>"application/msword"
		,"xls"=>"application/vnd.ms-excel"
		,"ppt"=>"application/vnd.ms-powerpoint"
		,"gif"=>"image/gif"
		,"png"=>"image/png"
		,"jpeg"=>"image/jpg"
		,"jpg"=>"image/jpg"
		,"mp3"=>"audio/mpeg"
		,"wav"=>"audio/x-wav"
		,"mpeg"=>"video/mpeg"
		,"mpg"=>"video/mpeg"
		,"mpe"=>"video/mpeg"
		,"mov"=>"video/quicktime"
		,"avi"=>"video/x-msvideo"
		,"3gp"=>"video/3gpp"
		,"css"=>"text/css"
		,"jsc"=>"application/javascript"
		,"js"=>"application/javascript"
		,"php"=>"text/html"
		,"htm"=>"text/html"
		,"html"=>"text/html"
	);

	$extension = strtolower(end(explode('.',$file)));

	return $mime_types[$extension];
}

?>

Usage Examples

Here are a couple of ways to use this function.

<?php

// simple calls to fetch mime type of a file
echo get_mime_type('example.doc'); // displays "application/msword"
echo get_mime_type('picture.jpg'); // displays "image/jpg"
echo get_mime_type('Harry_Potter.mov'); // displays "video/quicktime"

Advanced Example

This example is slightly more advanced. It will set the http header image/jpg and output the image file. It can be used for displaying an image from a php script.

<?php

$mime = get_mime_type('my_image_file.jpg'); // this will return "image/jpg"
header("Content-Type: $mime");
echo file_get_contents('my_image_file.jpg'); // output the image to the browser
?>