Random Banner with PHP

Twitter Facebook Pinterest Google+ Stumbleupon LinkedIn


This is a quick tutorial which shows how easy it is to make a random banner script with PHP. We will use a PHP array of images which is populated by a given directory and select a random index from the array to be the banner.

For this example I have chosen to list the files from a directory as this will keep the script fairly dynamic without the need of a database. The script could be easily modified to use a database but we can come back to that later on if we need to.

To start off all you will need is a folder with several banners and a page to display them on.

$dir will be the directory you have created to grab the images from, it is important to make sure this folder only contains banners.
$banners will be the array of images found in the given folder.


 $banners = array();
  $dir = 'res/banners/';
  if ($handle = opendir($dir)) {
  while (false !== ($file = readdir($handle))) {
  if($file != "." && $file != ".."){
  $banners[] = $file;
  }
  }
  closedir($handle);
  }

  $rand = array_rand($banners,1);
  echo "<img src='".$dir.$banners[$rand]."' alt='banner'/>";   

The code above uses a few handy built in PHP functions:
opendir()
readdir()
array_rand()
print_r()


Posted by Adi on February 20, 2009

Twitter Facebook Pinterest Google+ Stumbleupon LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *