PHP

Posts about the server side scripting language PHP

A Garbage Collection Mechanism In PHP

Garbage collection is a term for a maintenance function in a class or script that you don't want to run every time the script is run.  The main function of the script is to clean up anything that the script has used previously, but is now not important in the general running of the system and can be removed with no ill effects.  However, it is important that the garbage collection is not run every time the script is run as it may have a detrimental effect on the speed of the system.  To get around this we can use a random number generator to generate a number within a range, and use this to test if the garbage collection function should be run.  Here is the code.

www.php.net

By far the best resource for finding information about PHP and all of the functions available is from the PHP website. Not only can you view the PHP documentation, but you can also download PHP and many of the extensions like the Smarty template system.

Each PHP function and section has its own page with lots of detailed information about usage and instillation, which can be found quite easily on the site by entering the domain name followed by the function name you want to look up. If the function isn't found that the site points you towards a search results page.

PHP5 Filter Functions Part 2

Following on from the previous post about the PHP filter functions there are two more filter functions that require some extra explanation. These functions are filter_var_array() and filter_input_array().

They work in much the same way as filter_var() and filter_input() but they accept an array as the input. This enables you to sanitize or validate many different variables at the same time.

The first step in using these functions is to create an argument array. This is an associative array of data identifiers that allow you to set filter and sanitizer flags for different values. For example, assume that the following array is going to be used.

PHP5 Filter Functions Part 1

The filter functions are part of the PECL library and should come as standard on most PHP 5 installs. If they aren't there then ask your server administrator to install them.

The filter functions where created to avoid developers having to write lots of unmaintainable code in order to check the validity of variables and to sanitize these variables once validated. So rather than using many different functions and regular expressions to tell if a value is a number, a boolean or even a URL, you can just use these filter fucntions.

The main functions that you might be interested in are filter_var() and filter_input(). The filter_var() function is used to validate a single input, the parameters are:

PHP Page Redirection

To redirect to a different page using PHP you can use the header() function with the parameter 'Location: ' and the destination of the redirect.

header('Location: http://www.hashbangcode.com');

However, if any headers are sent before this function call then the script will fail. To get around this you can either ensure that nothing is printed out on the page, or if that is not possible for some reason then you can use a JavaScript redirect. The headers_sent() function will allow you to see if any headers have been sent to the browser yet, if they have then you will need to use the JavaScript redirect like this:

PHP Function To Work Out Average Values In Array

Working out the average of a bunch of values is quite a common task, but rather than looping through the array, adding together values as you go and the using the count() function to find out the average at the end.

function average($array)
{
 $total = 0;
 foreach ($array as $item) {
  $total += $item;
 };
 return $total/count($array);	
}

However, a much simpler way of doing things is just to use the PHP function array_sum(), which adds up all of the values in the array. Because this is done by the PHP engine it should take less time than using a for loop.

function average($array) {
 return array_sum($array) / count($array);
}

Tests show that the second function is only just faster when using short (2 or 3 items) arrays, but the second function is significantly faster when looking at longer (10 or more) arrays.

Biased Random Value From Array With PHP

Sometimes you will want to get a random value form an array in a biased random way, that is, you will want certain values to be returned more than others. Here is a function that will generate a single key from an array, with a greater change of a higher value being retrieved.

function biasedRandom($numbers){
 $total = 0;
 foreach($numbers as $number=>$weight){
  $total += $weight;
  $distribution[$number] = $total;
 };
 $rand = mt_rand(0,$total-1);
 foreach($distribution as $number=>$weights){
  if($rand<$weights){
   return $number;
  };
 };
}

This function is used in the following way.

Discover Auto Increment ID After MySQL Insert With PHP

Inserting a value into a database with an auto incrementing field is quite common. Once you insert the new row you would expect that you need to do another query to get the newly created ID.

Another option is to use the mysql_insert_id() function to retrieve the ID created by the last insert statement.

// insert
$sql = 'INSERT INTO table(colum1, colum2) VALUES(1, 2);';
mysql_query($sql);
 
// get new id
$id = mysql_insert_id();

The $id variable will now contain your most recently inserted ID.

PHP Password Generator

Here is a very simple function that will generate a string of random characters, ideal if you want to create a password for a new user.

function generatePassword($length=10)
{
 $pass = '';
 $parts = array_merge(range(0, 9),range('a', 'z'),range('A', 'Z'));	
 for ($i=0; strlen($pass) <= $length; $i++) {
  $pass .= $parts[array_rand($parts)];
 }
 return $pass;
}

Use the function like this.

echo generatePassword();

To create a longer password string just pass a parameter with the function.

echo generatePassword(5);

 

Extract Links From A HTML File With PHP

Use the following function to extract all of the links from a HTML string.

function linkExtractor($html)
{
 $linkArray = array();
 if(preg_match_all('/<a\s+.*?href=[\"\']?([^\"\' >]*)[\"\']?[^>]*>(.*?)<\/a>/i', $html, $matches, PREG_SET_ORDER)){
  foreach ($matches as $match) {
   array_push($linkArray, array($match[1], $match[2]));
  }
 }
 return $linkArray;
}

To use it just read a web page or file into a string, and pass that string to the function. The following example reads a web page using the PHP CURL functions and then passes the result into the function to retrieve the links.