Programming

Programming

PHP Array Push Pop Shift and Unshift

Overview

Many if not all PHP developers will come across arrays in their day to day programming. Arrays allow you to store ‘rows’ or ‘blocks’ of information. PHP comes with plenty functions that can be used to create, manage and simplify the use of arrays. I will focus on four functions that allow you to add and remove elements from an array. I will also show you how to access the first and last elements of an array using these functions.

PHP Array Functions

PHP Array Push Pop Shift and Unshift

For each of the four functions, I will give a short overview of what each one is used for as well as alternative functions that can be used to achieve the same result. Remember that each of the four functions will reset the internal pointer for the array when used causing your ‘foreach’ function to start at the beginning of the array.

PHP Push Array – array_push()

Add one or more elements onto the end of array. Returns the number of elements in the new array.

Standard method using array_push();

// create our array with 1 element
$arr = array("one");
// $count will be 3 and $arr will now be array("one","two","three");
$count = array_push($arr,"two","three");

Alternate method using $arr[]

tip! Using this method can be faster than using array_push since there is no overhead of calling an actual function.

// create our array with 1 element
$arr = array("one");
// $arr will now be array("one","two");
$arr[] = "two";
// $arr will now be array("one","two","three");
$arr[] = "three";
// $count will be 3
$count = count($arr);

Alternate method using array_merge();

// create our array with 1 element
$arr = array("one");
// alternate method using array_merge()
$arr = array_merge($arr,array("two","three")); // $arr will now be array("one","two","three");
$count = count($arr); // $count will be 3

PHP Pop Array – array_pop()

Removes and returns the value of the last element of an array. Returns NULL if array is empty or not set.

Standard method using array_pop();

// create our array with 3 elements
$arr = array("one","two","three");
// $value will be "three" and array's value will now be array("one","two");
$value = array_pop($arr);

Alternate method using array_slice();

// create our array with 3 elements
$arr = array("one","two","three");
// alternative method using array_slice()
$value = $arr[count($arr)-1]; // $value will no be "three"
$arr = array_slice($arr, 0, -1);   // $arr will now be array("one","two");

PHP Shift Array – array_shift()

Removes and returns the value of the first element of an array. Returns NULL if array is empty or not set.

Standard method using array_shift();

// create our array with 3 elements
$arr = array("one","two","three");
// $value will be "one" and array's value will now be array("two","three");
$value = array_shift($arr);

Alternate method using array_slice();

// create our array with 3 elements
$arr = array("one","two","three");
$value = $arr[0]; // $value will now be "one"
$arr = array_slice($arr, 1); // array's value will now be array("two","three");

PHP Unshift Array – array_unshift()

Add one or more elements to the beginning of an array. Returns the number of elements in the new array.

Standard method using array_unshift();

// create our array with 3 elements
$arr = array("three","four","five");
// $count will now be 5 and array will hold one - five
$count = array_unshift($arr,"one","two");

Alternate method using array_slice();

// create our array with 3 elements
$arr = array("three","four","five");
// $count will now be 5 and array will hold one - five
$arr = array_merge(array("one","two"),$arr);
$count = count($arr);

PHP stdin Command Line Input From User

Overview

In C++ it is called cin, and in perl it is $variable = <STDIN> however what is the equivalent of cin and STDIN for PHP?

In PHP is is similar to perl in that we use php’s I/O stream called stdin. The syntax looks something like this:

php://stdin

Reading User Input From Command Line

To read a user’s input from the command line we use stdin which as I mentioned before, is an I/O stream. Since stdin is an input stream, it can only be opened as read-only. There are two other I/O streams which are stdout and stderr and as they are output stream, they can only be opened in write mode. Opening stdin and reading from it won’t be that difficult and hopefully the example below will show how useful and easy it can be to capture a users input from the command line or other information from stdin and display it back to the user.

PHP stdin Command Line Input From User

The below script will capture a user’s name and then display it to the user.

<?php

// show them a message to enter their name
echo "Tell us your name: " . PHP_EOL;

// the script will wait here until the user has entered something and hit ENTER
$name = read_stdin();

// This will display the thank you message including their name they entered.
echo "Thank you $name. Welcome to my site" . PHP_EOL;

// our function to read from the command line
function read_stdin()
{
	$fr=fopen("php://stdin","r");	// open our file pointer to read from stdin
	$input = fgets($fr,128);	// read a maximum of 128 characters
	$input = rtrim($input);		// trim any trailing spaces.
	fclose ($fr);			// close the file handle
	return $input;			// return the text entered
}

?>

Final Note

Reading from the command line can be useful for creating php scripts that run from the command line. It can be used to capture the user’s decisions such as specifying the install location or setting up config preferences for a new website.

PHP Increase Memory Limit Using Htaccess, Apache Or PHP

Overview

Most of us have come across this error: “Fatal error: Allowed memory size of xxxxxx bytes exhausted (tried to allocate yyy bytes) in ….” in the php error log files.

In php, running out of memory in usually a sign that your php script is not too well written or has a bug or two in it. It could also be caused by script that have to process large amounts of data at once. Sometime even well designed php scripts still require more memory than usual especially if it is handling large amounts of data or when trying to read large files into memory.

PHP Increase Memory Limit Using Htaccess, Apache Or PHP Script

Luckily in php, increasing the memory limit is an easy task to do and can be done in a number of ways. Below I will show you how to increase (or even decrease) the memory limit using either htaccess, apache and even inside the php script itself.

Setting PHP Memory Limit inside PHP Script

Inside your php script that requires the increase in memory, you can add the following line which increases the memory limit just for that page. So putting this at the top of the script can help you handle larger amounts of data.

<?php

// note that memory_limit is case sensitive!
ini_set('memory_limit','64M');

// rest of your code follows

Setting PHP Memory Limit in .htaccess

Setting a memory limit in .htaccess is also straight forward. Add a line into your .htaccess file. Note that this will affect any php files within that folder and subfolders. You won’t need to restart apache when updating the htaccess. Be careful as any typo’s in the htaccess file will prevent the website from loading correctly.

php_value memory_limit 64M

Setting PHP Memory Limit in php.ini config file

If you want to set the memory limit within PHP itself, then edit the php.ini file which is usually found under /etc/php/apache2/php.ini under Debian and find the line shown below and change it to whatever you need. This will affect all php scripts running under your server so be careful with this value.
Note: you will have to restart apache for this change to take effect

memory_limit = 64M

Setting PHP Memory Limit in Apache

Inside apache, find the virtual host that needs the increase in memory limit and add the line as shown below in italics.
Note: you will have to restart apache for this change to take effect

<VirtualHost *:80>

# apache settings for virtual host

php_value memory_limit 64M

# other settings etc. follow as usual.

</VirtualHost>

Conclusion

Needing more memory for a php script can be frustrating, luckily you are able to increase the php memory limit for your website or just a specific subfolder of your site. It is easy to increase the limit using either htaccess, apache or within the php script.

Override The Default PHP Execution Timeout Limit

Overview

In many programming language there is always a chance that your code will enter an infinite loop and get stuck for a long time. There is also a chance that a script may be processing large and complex dataset which causes it consume large amounts of server resources for a long time. Which affects other programs or websites that are running on the same server. In most cases this would be useful, however sometimes you will need to allow the script to complete even if it takes a long time and consumes a chunk of a server’s resources.

If this is the case, you can override the default PHP execution limit, which is generally around 30 seconds and set it to a much higher (or lower) timeout limit. You can even remove the time limit although this isn’t generally recommended. As you will see, PHP has introduced a PHP Execution Timeout which basically limits the amount of time a PHP script is allowed run until it is cancelled by the PHP server.

Override The Default PHP Execution Timeout Limit

I will show you a number of ways to extend the maximum execution time of a PHP script.

 

Setting the PHP execution limit in php.ini

Edit your php.ini file which is usually under ‘/etc/php5/apache2/php.ini’ in Debian Linux and scroll to the line which has the max_execution_time option. Want to remote the time limit? Setting the limit to 0 (zero) will remove the PHP execution timeout and possibly cause the PHP script to run forever.

max_execution_time = 600

 

Setting the PHP execution timeout using set_time_limit()

You can override the PHP execution time directly in a PHP script by using the set_time_limit() function. Setting the limit to 0 (zero) will remove the PHP execution timeout and possibly cause the PHP script to run forever.

<?php

// set the PHP timelimit to 10 minutes
set_time_limit(600);

// rest of your code will be able to run for the next 10 minutes before timing out

?>

 

Changing the PHP execution time using ini_set()

Just as above, you can also override the PHP timeout limit in a PHP script by using the PHP ini_set() function. Setting the limit to 0 (zero) will remove the PHP execution timeout and possibly cause the PHP script to run forever.

<?php

// set the PHP timelimit to 10 minutes
ini_set('max_execution_time',600);

// rest of your code will be able to run for the next 10 minutes before timing out

?>

 

Override PHP execution time in .htaccess file

Overriding the default PHP execution timeout can also be done inside an .htaccess file by using the php_value directive and using it to set the value of max_execution_time. Setting the limit to 0 (zero) will remove the PHP execution timeout and possibly cause the PHP script to run forever.

# set timeout to 10 minutes
php_value max_execution_time 600

Final Words

Increasing the timeout limit can be very useful but should be used with caution. Removing the time limit can be done by setting the limit to 0, but again, use with caution. Timeout limits are there for a reason and should only be used when other options are not available or viable.

PHP Ping Script To Check Remote Server Or Website

Overview

Ever needed a quick php code snippet to perform a ping to check if a remote server or website is up? Then see the code below which contains two variations of a ping function that will show you how to ping from php using a PHP Ping Script. The first version uses exec() and the second version uses fsockopen().

PHP Ping Website

The advantage of the second function is that it can connect to a specified port which allows you to also check if a port or service is available on your server. Great if you want to check if your Website is still running on port 80 or if your MySQL service is still responding.

PHP Ping Script To Check Remote Server Or Website

A PHP Ping Script can be very useful to check if your website or server is up before attempting to connect to it resulting in you having to wait for ages while the program or script to eventually timeout.

Our first version using PHP exec() to ping the server.

First example is a simple example that will send a standard ping.

<?php

/* our simple php ping function */
function ping($host)
{
	exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($host)), $res, $rval);
	return $rval === 0;
}

/* check if the host is up
	$host can also be an ip address */
$host = 'www.example.com';
$up = ping($host);

/* optionally display either a red or green image to signify the server status */
echo '<img src="'.($up ? 'on' : 'off').'.jpg" alt="'.($up ? 'up' : 'down').'" />';

?>

Our alternate PHP Ping Script using fsockopen().

Our second example is by far more useful as it accepts a port as the parameter. This allows us to check specific services on the server. Using port 80 in most cases will test the website, or 3306 will try connect to a mysql server.

<?php

function ping($host,$port=80,$timeout=6)
{
	$fsock = fsockopen($host, $port, $errno, $errstr, $timeout);
	if ( ! $fsock )
	{
		return FALSE;
	}
	else
	{
		return TRUE;
	}
}

?>

Useful Example of Using PHP Ping Script

We can use this ping function to allow us to provide our users with a better message rather than seeing our site is down.

<?php

$host = 'www.example.com';
$up = ping($host);

// if site is up, send them to the site.
if( $up ) {
	header('Location: http://'.$host);
}
// otherwise, take them to another one of our sites and show them a descriptive message
else {
	header('Location: http://www.anothersite.com/some_message');
}

?>

Now if the site is up, they will get sent to your site. Otherwise they will be sent to www.anothersite.com and shown a message.

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

Overview

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.

<?php

/* 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(
	array(
		"first_name" => "Darian",
		"last_name" => "Brown",
		"age" => "28",
		"email" => "darianbr@example.com"
	),
	array(
		"first_name" => "John",
		"last_name" => "Doe",
		"age" => "47",
		"email" => "john_doe@example.com"
	)
);

/* encode the array as json. this will output [{"first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr@example.com"},{"first_name":"John","last_name":"Doe","age":"47","email":"john_doe@example.com"}] */
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.

<html>
<head>
	<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>

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

	<script type='text/javascript'>
	$(document).ready(function(){
		/* 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.email + ' ' + val.age + '</li>');
			});
		});

	});
	</script>

</body>
</html>

 

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

Overview

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.abort();
		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

Overview

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

PHP

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.

<?php

/* 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 http://php.net/manual/en/function.date.php.
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.

<?php

/* 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);

?>

MySQL

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

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();

</script>

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

</script>

Perl

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();

Linux

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

Specify Favicon.png In Html

Overview

Favicons are the tiny icons that usually appear next to the url in your browser. Favicons add a nice flair to your site and they are typically easy to implement.

specify favicon.png in html

Image showing an example of a favicon in showing in google chrome

Compatibility

For compatibility with all browsers stick with .ico is the way to go, however png favicons are support by most modern browsers. You can also specify both a favicon.png and favicon.ico in your html code to ensure complete compatibility.

Specify Favicon.png In Html

To specify favicon.png in html all you need to do is include the following line in the head of your html.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="icon" type="image/png" href="http://www.thecave.info/favicon.png" />
  </head>

Why use favicon.png

I have found that is it usually easier to save an image as a png as opposed to ico. Additionally, a png can be smaller than ico. There are other websites that will allow you to upload an image and convert it to an ico should you wish to have both a ico and png version of your favion.

Overlay HTML Over Flash Object

Overview

When building websites that use HTML and Flash, you may find that the flash movie appears above all of your other content such as drop down menus, div boxes and shadow-boxes. It can happen even when you manually enter in the z-index of those elements.

A Note About Z-Index Layering

The z-index of an item determines the layer an item will be rendered on. The higher the z-index number, the closer to the top layer an item will appear. So an item with a z-index of 10 will appear in front of an item with a z-index of 9.

Setting The Z-Index Of An Item

<style>

.your-item {
    z-index: 1000; /* or what whatever number you like */
}
</style>

Overlay HTML Over Flash Object

It can be very frustrating when flash appears above html content and menu. The reason this occurs is that DHTML uses layers to decide which elements stack in front of others. Just as a stack of cards are layered on top of each other. Content like Java or Flash that is embedded into the page ignores the layer order and is by default rendered on the highest layer of the page.

Older browsers are still stuck with this issue but luckily most modern browsers these days have the ability to layer the embedded content along with the rest of your elements. All you need to do to overlay html over flash object is to set the `WMODE` parameter to `transparent` and now it will obey your layering order which is controlled by the swf’s z-index. Other values for WMODE are ‘window’ (default), ‘opaque’, or ‘transparent’.

I will show you two ways on how to enable WMODE when embedding flash in your website.

1st option – Inline Embedding

To set the `WMODE` you need to set it in two place which I have highlighted yellow in the below example.

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="380" height="190" id="YourFlashMovie" align="middle">
	<param name="allowScriptAccess" value="sameDomain" />
	<param name="allowFullScreen" value="false" />
	<param name="movie" value="AS3_File_Upload2.swf" />
	<param name="quality" value="high" />
	<param name="wmode" value="transparent" />
	<param name="bgcolor" value="#333333" />
	<embed src="YourFlashMovie.swf" quality="high" wmode="transparent" bgcolor="#333333" width="380" height="190" name="YourFlashMovie" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>

Now all you need to do is place the flash movie where you want it and optionally set z-index to override the layer it appears on.

2nd option – swfobject (javascript include function)

Alternatively, you can use swfobject and specify similar parameters to acheive the same effect. Swfobject is a javascript file available free from http://code.google.com/p/swfobject/ and can be used to simplify the process of embedding flash into your website.

After downloading the swfobject.js from google code, include it into your page using.

<script type="text/javascript" src="swfobject.js"></script>

And then execute the function as shown below but ensure that you set the param to include `WMODE` as highlighted yellow.

<script type="text/javascript">

var flashvars = {};
var params = {wmode:'transparent'};
var attributes = {};

// divContainer is the div block that will then hold the embedded flash object.
swfobject.embedSWF("flashFile.swf", "divContainer", "300", "120", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

</script>

Prevent Menu From Appearing Behind Flash Object

Once you have completed the above, you can now change the order/layer the flash appears in your page. Your flash object should now obey the layer ordering and setting the z-index on both your flash object and menu should do the trick

Remember: The higher the number, the higher the layer. Higher layers appear on top of lower layers.

<style>

#YourFlashMovie {
    z-index: 1000; /* or what whatever number you like */
}

.yourMenuContainer {
    z-index: 1001; /* or any number as long as it is higher then #YourFlashMovie */
}