PHP

Posts about the server side scripting language PHP

Simple PHP Script To Hide An Email Address In An Image

Spam is a problem. You want to allow people who genuinely want to get in touch to see your email address, but doing this invariably leads to you getting thousands of spam emails.

One solution is to hide your email address in an image, but it can be a pain to create an image for every email address you need. A better solution is to use the PHP GD functions to create an image at runtime so that your email address is displayed, but is completely unreadable to spammers.

To to this you will need to create an image tag on your website, here is an example.

Getting All Permutations Of An Array In PHP

Here are two ways in which you can figure out all of the different permutations of an array.

The first is using a recursive algorithm. This nibbles apart the array and sticks it back together again, eventually resulting in all of the different permutations available.

Display Wordpress Feeds On Your Site With SimplePie

You can display your latest Wordpress posts anywhere on your site by using an RSS reader called SimplePie and a few lines of code. SimplePie is a fast and efficient RSS reader, and it will also cache feeds to reduce the amount of processing time taken.

Download simple pie from the website and upload the simplepie.inc file to your web server. Next include the following section of code anywhere on your site that you want to display the latest post on.

Force File Download With PHP

When you supply files that web browsers can open they are usually opened inside the browser, rather than being downloaded. This can be annoying, especially where PDF documents are involved. You could supply the files in a compressed format in order to force users to download them, but this is also annoying as the user then has to uncompress the file.

You can force the web browser to supply the file as a download by using the header() function in PHP. The following little bit of code will take any filename and supply it as a download.

<?php
$file = $_GET['file'];
header('Content-type: octet/stream');
header('Content-disposition: attachment; filename='.$file.';');
header('Content-Length: '.filesize($file));
readfile($file);
exit;
?>

All you have to do is link to this script with the argument being the file name you want your users to be able to download.

Passing Values By Reference In PHP

For most functions it is normal for have the function return the output of a calculation. With PHP it is also possible to pass values to the function by reference. A better way of saying this is rather than pass the value of the variable you pass a pointer to the variable itself. When you do this anything that you do to the variable inside the function is also done outside, so if you interact with the variable again it will contain a different value.

The ampersand (&) character is used in the parameters of the function to stipulate that a parameter will be passed by reference.

Here is an example of this at work.

Recursive Directory Listing With PHP

Use the following function to list the contents of one or more nested directories.

function recursive_directory($dirname,$maxdepth=10, $depth=0){
 if ($depth >= $maxdepth) {
  return false;
 }
 $subdirectories = array();
 $files = array();
 if (is_dir($dirname) && is_readable($dirname)) {
  $d = dir($dirname);
  while (false !== ($f = $d->read())) {
   $file = $d->path.'/'.$f;
   // skip . and ..
   if (('.'==$f) || ('..'==$f)) {
    continue;
   };
   if (is_dir($dirname.'/'.$f)) {
    array_push($subdirectories,$dirname.'/'.$f);
   } else {
    array_push($files,$dirname.'/'.$f);
   };
  };
  $d->close();
  foreach ($subdirectories as $subdirectory) {
    $files = array_merge($files, recursive_directory($subdirectory, $maxdepth, $depth+1));
  };
 }
 return $files;
}

Use this in the following way.

PHP Headers Already Sent Error

Try running the following PHP script.

<?php
 echo 'browser output';
 session_start();
?>

You will either see normal output or get the following error messages.

This is because when you try to start the session it adds items to the headers outputted by the browser, including the setting up of cookies. To stop this happening you need to ensure that the session_start() function call is put before any output from the browser. This is the case for all header modifying functions including set_cookie() and header().

Custom Error Handling In PHP Using set_error_handler()

The set_error_handler() function can be used in PHP to allow you to catch any run time errors and act accordingly. This function can take two parameters:

  • Error Handler : This a string which is the name of the function that will be called if an error is encountered.
  • Error Types (optional) : This is an optional parameter used to tell PHP on what error codes to act. This is the same error reporting setting.

The function that is defined in the function must have the following footprint as a minimum.

function handler($errno,$errstr)

You can also get a lot more information out by using other parameters.

function handler($errno,$errstr,$errfile,$errline,$errcontext)

Here is some code that will print two errors to screen with as much information as possible.

Append One Array To Another In PHP

Appending arrays in PHP can be done with the array_merge() function. The array will take any number of arrays as arguments and will return a single array. Here is an example using just two arrays.

$array1 = array('item1', 'item2');
$array2 = array('item3', 'item4');
$array3 = array_merge($array1, $array2);
print_r($array3);

Will print out.

Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

You can also create arrays using the array command inside the parameter list.

PHP Random Quote Generator

The following code loads the contents of a text file and randomly displays a line from it. You can use this to display a random quote on a page every time it loads.

$file= "quotes.txt";
$quotes = file($file);
srand((double)microtime()*1000000);
$randomquote = rand(0, count($quotes)-1);
echo $quotes[$randomquote];

It works by loading a file into memory and picking a line from that file at random. Here is a sample file you might want to use.

This is the first quote - Person One
This is the second quote - Person Two

Fill this with your own quotes and you are away.