PHP

Posts about the server side scripting language PHP

Fastest Way To Match String With PHP

There are many ways to find a string within another string using PHP, but which one is the quickest? I did the same sort of test that I have done with double or single quotes and downloading web pages with a few of the string matching functions available in PHP.

I first generated a very long string that could be used in the string matching functions. The following for loop generates a string containing "iteration 0 and iteration 1 and iteration 2..." right up until "iteration 4999 and".

$testString = '';
for ($i=0; $i < 5000; $i++) {
 $testString .= "iteration " . $i . " and ";
}

This was then passed to a number of string matching functions. This included the regular expression libraries contained in ereg() and preg_match(). The strpos() and strstr() functions were used as these are another common way of string matching, as well as some of their variants for matching case insensitive strings.

Secure Include Files In PHP

Including files in any PHP program is a very common practice and is nothing out of the ordinary. However, problems can occur when a user navigates to a script file that has a function, but is meant to be included as part of the larger program. For example, if your system includes a file to delete something then if that file is run by itself then there is a chance that it will delete everything.

Of course there are other factors like database access, global variables and sessions that would cause any script to simply error and not cause a problem. However, it is good practice to make sure that any include file is only run when it is included, and not when it is run on it's own.

The following little snipped of code can be placed at the top of any include files to make sure that it can't be run outside of an include. The file in this example would be called "test.php".

Quickest Way To Download A Web Page With PHP

There are lots of different ways to download a web page using PHP, but which is the fastest? In this post I will go through as many different methods of downloading a web page and test them to see which is the quickest.

Here is a list of the different methods.

  • The PHP curl library.
  • Snoopy the PHP web browser. Bascially a wrapper for fsockopen.
  • fsockopen().
  • fopen() with feof().
  • fopen() with stream_get_contents().
  • file() and then implode().
  • file_get_contents() function.

Each method will be run and will retrieve the contents of a web page 50 times each in order to get a decent spread of times. On each run the time will be recorded into an array, this array will then be used at the end to calculate some statistics.

Serialize And Unserialize With PHP

If you have an object or array that you want to save until a later you can use the serialize() and unserialize() functions. The operation of the functions are straightforward. To serialize() an array just pass the serialise function the array like this.

$array = array(1,2,3,4);
$serializedArray = serialize($array);

Now when we print the serialized array out we get the following.

a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;}

This contains all of the data needed to recreate our array. Be careful not to edit this string because it will not work if you want to unserialize it and get the array back. You can store this string in a file or a database so that you can recreate the exact same array at a later date.

The PHP array_flip() Function And Detecting Functions

The array_flip() function in PHP is used to swap the values of an array with the keys. Take the following array.

$array = array('key1'=>'value1', 'key2'=>'value2');

To exchange all the values with the keys we pass it through the array_flip() function.

$array = array_flip($array);
echo '<pre>'.print_r($array, true).'</pre>';

This prints out the following:

Array
(
 [value1] => key1
 [value2] => key2
)

If any of the values are the same then the highest key is overwritten. The following array:

$array = array('a', 'a', 'a', 'b');

Will produce the following array when passed through array_flip().

Time Calculator In PHP

Use the following function to work out how long it has been since an event in years, months, weeks, days, hours, minutes and seconds.

function getAge($year,$month,$day,$hour=0,$minute=0,$second=0){
 $age = mktime($hour,$minute,$second,$month,$day,$year);
 $age = time()-$age;
 return array('years'=>$age/60/60/24/365,
  'months'=>$age/60/60/24/12,
  'weeks'=>$age/60/60/24/7,
  'days'=>$age/60/60/24,
  'hours'=>$age/60/60,
  'minutes'=>$age/60,
  'seconds'=>$age);
}

The practical use of this function is that you can work out how old someone is from their birthday. Here is an example of the function in use.

// someone's birthday
echo '<pre>'.print_r(getAge(1984,10,4),true).'</pre>';

Which would output the following:

Print A Current Copyright Notice With PHP

One thing that is inexcusable on any website is printing a copyright notice that is out of date. There are many protagonists of this crime and it is fairly easy to spot.

However, rather than go through all of the pages on your site and hand code in the copyright notice you could just put in the following little bit of PHP.

Copyright <?php echo date("Y"); ?> #! code

This will print off a current copyright notice, no matter what the year is.

Copyright 2008 #! code

The date() function is built into PHP and takes two parameters. The first (required) parameter is a format string for the date. In this example we are giving a single capital "Y", which returns a numeric representation of the year with 4 digits.

Calculate Distance Between Two Geographical Points With PHP

Use the following function to work out the distance between two geographical points. Geographical points are usually longitude and latitude, in degrees. The first thing to do is to convert these values into radians (using the deg2rad() PHP function) so that we can work with them. The four basic parameters used are the longitude and latitude values for the two points. The optional fifth value is to have the end value returned in miles, rather than kilometres.

Shortening Long URLs With PHP

Print out a full URL for a link will sometimes mess up your formatting, especially if you URL is quite long. This might be the case if you are linking to a Google search page, or have an automated script that shows numerous URLs of indeterminate length. The following function will reduce any URL longer than 45 characters by splitting it in two and join them up with a simple string.

function shortenurl($url)
{
 if ( strlen($url) &gt; 45) {
  return substr($url, 0, 30)."[...]".substr($url, -15);
 } else {
  return $url;
 }
}

You can use the function in the following way.

Preparing A URL With PHP

There might be many instances where you will create a program in PHP that takes a URL as input and does something with the address. This might be a site analysis or an image resize, but whatever the use is, you need to be sure that the URL will work or at least has the same format.

What users tend to leave out of a URL string is the http:// bit at the start. You could validate the URL to force the user to do this, but you will end up annoying a few people. By far the best way of making sure that the URL has the http:// bit at the start is by adding it behind the scenes. The best way to this is to remove the http:// from the start of the string, even if it isn't there and then add it back on.