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




Regex Reverse Match And Replace All But Specified Characters


We can use regular expressions to specify a list characters we want to either strip out of a string or replace them with other characters however this article is aimed more on how to do a regex reverse match and replace (also knows as a negative replace) where we specify the characters we DO NOT want to be stripped out which can be very useful for sanitising and cleaning out strings and prevent MySQL injections or cross-site scripting attacks. In other words we replace everything but the string specified.

Sounds simple enough yet I found it ever so difficult on how to perform this which is why I am posting it here to save others the time.

Regex Reverse Match

The below examples use the regular expression pattern /[^a-zA-Z0-9\s]/ which basically is just specifying a list of characters (being upper and lower case letters, numbers and spaces). But the big difference is the ^ (caret symbol) is inside the square brackets which tells the regular expression that it is a negative search. ie, match and strip all but the ones listed.

Remember… if we wanted to remove the list of characters specified by the expression’s pattern, then we simply exclude the ^ which mean the resulting pattern to include a list of characters would look like so: /[a-zA-Z0-9]/.

Secondly the second parameter is and empty string which will tell the function to replace the string with nothing.

Note! that if the ^ (caret) was outside the square brackets it would then specify matches at the beginning of a sentence. Just as a $ (dollar symbol) at the end of the sentence would specify matches at the end of the sentence. In this case, the ^ (caret) is inside which denotes an exclusion of characters.

PHP Reverse Replace


/* our string we will be working on */
$str = "A string - with, awful characters$@!.";
/* use php's preg_replace to execute the regular expression and echo the result */
echo preg_replace( '/[^a-zA-Z0-9\s]/', '', $str );
/* the output from the above will be "A string with awful characters" */


Javascript Reverse Replace

<script type="text/javascript">

/* our string we will be working on */
var str = 'A string - with, awful characters$@!.';
/* use  javascript's replace() function to execute the regular expression and then store the result */
var str = str.replace(/[^a-zA-Z0-9\s]/g,'');
/* the variable `str` from the above will be "A string with awful characters" - all nasty characters are removed */


Validate IP Address PHP And Javascript Examples


Below is a similar post to my other post on validate email addresses example except in this post we will validate an IP address instead of an email address. I have also provided simple and straight forward code snippets for Javascript and PHP. It uses a regular expression to test if the string passed to is a check the IP address is valid.

Validate IP Address

Validate IP Address

Validate IP Address PHP And Javascript Examples

The two types of IP Address Validation we will cover are:

I have included both PHP and Javascript Email Validation Examples. It works perfectly for me and hope it will save you hours of time trying to find it out for yourself. Please let me know in the comments if you have any issues.

Validate IP Address In PHP With preg_match()


/* The IP to test (this IP is valid) */
$str = "";
/* use php's preg_match to execute the regular expression and store the result - which is either `0` for no match or `1` for a match */
$bValidIP = preg_match( '/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $str );


Validate IP Address In Javascript With test()

<script type="text/javascript">

/* The IP to test (this IP is valid) */
var str = "";
/* The regular expression pattern */
var pattern = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/g;
/* use  javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(str);



Not much explaining I can do. Essentially there are two methods to validate IP address. First is validate IP in PHP and the second is how to validate IP address in javascript.

2D Sprite Animation Tutorial

What are sprite animations?

A sprite animation is basically a large image which contains a whole bunch of smaller images. Think of it as a film strip where each frame is the next piece of animation in the sequence. The idea of sprites is that you only need to load one image and it will contain all the smaller images needed to create the animation. You simply position the background position of the sprite and it will appear to animate the sprite. For more information on sprites, check out the css button sprite tutorial.

End Result Demonstration

Above is the finished example of a flame sprite and it is what this tutorial will show you. As you can see it appears as an animation, however we simply move the background position of the larger image to create the illusion of movement.

Why should you use 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.

Flame Ball Sprite

2D Sprite Animation Tutorial

Above is the large flame sprite image I am using to create the sprite animation for this tutorial. We use javascript to move the background position of the sprite image. In the below example, we do this every 100ms. To achieve smooth animation, we would need to achieve 25 frames per second, however this would increase the size of the sprite image, so we will do it a time frames per second.

Now for the code to get this all working

CSS Code

<style type="text/css">

#flameanimation {
	/* our flame sprite png */
	background: url(;
	width: 512px;
	height: 512px;


Javascript Code

Here is a quick javascript function to move the background position of the sprite animation to the next frame. We start at frame 1 and for each frame of animation we move 512px to the left since each frame is 512px wide by 512px high. Moving the background image positions every frame creates the illusion of movement, just as a movie is made up of 25 or 29 frames in a second.

<script type='text/javascript'>

	// call the next() function every 100 ms.
	setInterval(next, 100);

// first frame of animation
var frame = 1;

// move the sprite animation to the next frame
//	i.e. move background position to the next image in the sequence
function next()
	// Set the position of the sprite image 512px more to the left on each frame.
	var left = 512 * frame;
	// top stays 0 since all the images have Y positioned at 0
	var top = 0;
	document.getElementById('flameanimation').style.backgroundPosition = '-'+left+'px -'+top+'px'; 




Next we create the div tag where the sprite animation will be applied to.

<div id="flameanimation" title="Sprite Animation"></div>

Now as the javascript next() function runs, it will move the background image to the left which will create the illusion of animation.

flame sprite image obtained from

Pass a PHP Array to Javascript as JSON using AJAX and json_encode


You will mostly likely (or already have) reached a point where you have a PHP array and you need to be able to access that array from inside a Javascript function. You may wonder if it is possible to pass an array from PHP to Javascript. Fortunately I have created a tutorial on how this can be achieved. Below I will show you how to Pass a PHP Array to Javascript as JSON using AJAX. There are two parts to accomplish this task.

Creating The PHP Array

Firstly you need a PHP script which has the PHP array you want to pass back to Javascript. You encode the array into a JSON string using the PHP function `json_encode()`. We then echo the string into the PHP file to make it accessible to the AJAX function calling this script.

Call The PHP Script That Contains The PHP Array

Secondly we create an HTML which will contain the AJAX function to call the PHP script. We will use the jQuery `$.getJSON` function which converts the output from the PHP function ‘json_encode()’ into a JSON object. Once we have the JSON object, we can loop through it and use it as we require. We don’t really need to convert the JSON array to javascript array since we use jQuery’s ‘$.each()’ function to loop through the JSON array that is returned.

Pass a PHP Array to Javascript as JSON using AJAX

Below is the code that is to be placed into the PHP script. This file will be called by the jQuery `$.getJSON` function.


/* set out document type to text/javascript instead of text/html */
header("Content-type: text/javascript");

/* our multidimentional php array to pass back to javascript via ajax */
$arr = array(
		"first_name" => "Darian",
		"last_name" => "Brown",
		"age" => "28",
		"email" => ""
		"first_name" => "John",
		"last_name" => "Doe",
		"age" => "47",
		"email" => ""

/* encode the array as json. this will output [{"first_name":"Darian","last_name":"Brown","age":"28","email":""},{"first_name":"John","last_name":"Doe","age":"47","email":""}] */
echo json_encode($arr);


Javascript / HTML Code Snippet

Place this code into a file with the extension `.html`. The below code will call the above PHP script using AJAX and the jQuery function `$.getJSON`. The PHP script will have the PHP array encoded as a json string. Once the `$.getJSON` function returns, the Javascript function will have access to the PHP array that has been converted into a JSON object.

	<script type='text/javascript' src=''></script>

	<!-- this UL will be populated with the data from the php array -->

	<script type='text/javascript'>
		/* call the php that has the php array which is json_encoded */
		$.getJSON('json_encoded_array.php', function(data) {
			/* data will hold the php array as a javascript object */
			$.each(data, function(key, val) {
				$('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + + ' ' + val.age + '</li>');




Passing variables to PHP using JSON and AJAX

If you would like to pass some variables to PHP you can change the parameters as shown above. In my example below, I pass the variables name and age and then the PHP function could use these to search a database or file for that person and then return that specific information as a JSON array.

$.getJSON('json_encoded_array.php', {name:'Darian Brown',age:40}, function(data) {
	// ... handle response as above

How To Abort A Previous Ajax Request In jQuery


When using ajax to request a page or data, there will be occasions where you will need to cancel the ajax call. I found this useful after building a search as you type feature and I would abort the previous search and request a new ajax search each time they typed a new letter. Since their old word has changed to a new meaning, completing the old request is meaningless since the new word is an entirely different category. For example the typed fee and then they type `d` making the word feed. So I would abort a previous ajax request in jquery and issue a new ajax search on feed.

Additional uses for aborting an ajax request in jquery

Another reason may be that the page you are calling enters an infinite loop and stops the call from returning. Maybe you need to cancel a previous request before making a new request to prevent duplicate requests from being sent.

How To Abort A Previous Ajax Request In jQuery

Luckily jQuery has made this almost too easy as you can see by my example below.

/* our handler to the ajax request */
var xhr = null;

function goAjax()
	/* if there is a previous ajax request, then we abort it and then set xhr to null */
	if( xhr != null ) {
		xhr = null;

	/* and now we can safely make another ajax request since the previous one is aborted */
	xhr = $.ajax({
		type: "POST",
		url: "/some/url",
		data: "variables=whatever&var2=something",
		success: function(msg) {
			/* handle the ajax response */

Now you can call the goAjax() function as often as you like and it will cancel the previous ajax request if it hasn’t been completed before making a new request preventing duplicate requests from stacking up.

<a href='javascript:goAjax();'>Click me as much as you like</a>

And that is all there is to it. Simple and straightforward.

Real World Unix Timestamp Examples


Unix timestamps are extremely useful and can be used across my different programming languages and platforms. I will outline a couple programming languages that support timestamps.

  • PHPconvert timestamps to date in php
  • MysQLview example on how you can query timestamps from a MySQL Database
  • Javascriptthe Date() function in Javascript can use timestamps
  • Perlthe time() function in Perl can handle unix timestamps
  • Linuxreturn current timestamp in linux

Real World Unix Timestamp Examples


In PHP, you can convert a unix timestamp to a real time by using the php date() function. date() allows you to convert a timestamp that is supplied as the second parameter or if the second parameter is left out, it will convert the current timestamp to date.


/* this would display a time of 23 May 2011 17:12:pm */
echo date('d F Y H:i:a',1306134726);
/* and this would display the current time in the same format as above */
echo date('d F Y H:i:a');


The way the date is displayed is controlled by the flags passed to the function. Here we used the flags ‘d’, ‘F’, ‘Y’, ‘H’, ‘i’ and ‘A’. For a complete list of flags and to see a complete description of this function, visit
The PHP function time(), strtotime() and mktime() all return the current unix timestamp. If you wanted to, you can also get a time stamp 24 hours from now by using the following code.


/* get tomorrows timestamp */
$tomorrow = time() + (24 * 60 * 60);

/* or you can use strtotime to convert a natural string into a timestamp */
$tomorrow = strtotime('+24 hours');

/* and this will create a timestamp based on the date and time variables */
$timestamp = mktime($hour,$min,$sec,$month,$day,$year);



If you have a table that contains a column with a unix timestamp in it, you can convert it using the query below. It will return a column that contains rows of easy to read date and times.

SELECT FROM_UNIXTIME(column_name) AS real_time FROM `table_name`;


Javascript has a function called ‘Date()’ which allows you to use timestamps in javascript. Remember that since javascript is client side code (i.e. runs on the persons browser), the date shown is their own computer time, not the server time. To get the current timestamp in javascript, simple use

<script type="text/javascript">

/* get the current timestamp */
var timestamp = +new Date();


You can also convert a timestamp to a date by using the following javascript date functions.

<script type="text/javascript">

/* create a new date as of the current date */
var date = new Date();
/* you can also create a new date and pass a timestamp to create the date as of the timestamp */
var another_date = new Date(1306482441);

var day  = date.getDate(); // get the day that date relates to
day = day < 10 ? '0' + day : day; // add a 0 if less that 10
var month = date.getMonth() + 1; // returns month as 0 - 11
var year = date.getFullYear(); // 4 digit year (eg. 2011)
var hour = date.getHours(); // get hours
hour = hour<10?'0'+hour:hour; // pad with a 0
var minute = date.getMinutes(); // and minutes
minute = minute<10?'0'+minute:minute; // pad with 0
var second = date.getSeconds(); // get seconds
second = second<10?'0'+second:second; // pad with 0



In order to retrieve the current timestamp in Perl, you can make use of the time() function which is the same as PHP.

my $timestamp = time();


Using the ‘date’ command in linux will print out the date specified by the parameters passed to it. We will use the %s flag to tell it to print the seconds passed since ‘1970-01-01 00:00:00 UTC’ (i.e. it will print out the current timestamp).

date +%s

Validate Email Addresses – Javascript and PHP Example

Overview – Validate Email Addresses – Javascript and PHP Example

In todays article I will show provide you with source code validate email addresses using either Javascript or PHP. It uses a regular expression to test if the string passed to is a valid email address and returns true or false in either case. It works well for me and will hopefully do the trick for you.

Javascript Example using the function: test()

<script type="text/javascript">

/* validate an email address */
function validateEmail( em ) {
	var pattern = /^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i;
	return (pattern.test(em)) ? true : false;


In order to use the javascript validate email address function, simply include the above function in your javascript or separate include file and then call it using

<script type="text/javascript">
var bValidEmail = validateEmail('');

PHP Example using the function: preg_match()


/* validate an email address */
function validateEmail( $em ) {
	$pattern = '/^[a-z\d]+(?:[\-\.\_][a-z\d]+)*[a-z\d]+@[\w\d]+(?:[-\.][a-z\d][a-z\d\-]*[a-z\d])*[a-z\d]+\.([a-z]{2,4})(\.([a-z]{2,4}))*$/i';
	return preg_match($pattern,$em) ? true : false;


In order to use the php validate email address function, simply include the above function in your php or separate include file and then call it using

$bValidEmail = validateEmail('');

Validate Email Address Online

Use the form below to check email address is valid. Simply enter an email into the box below and hit ‘validate’ to validate the email address online. It simply makes sure the format of the email address is correct and does not verify that the email address actually exists or belongs to anyone.

Validate Email Address Online

You can get the code used to test the email address in this example by clicking here.
Enter Email Address and Click Validate