Random banner or header rotation

Posted by Planeta Srbija | 15.6.10 | | 1 comments »

Showing a different header or page background picture each timr the page loads can look pretty refreshing. There are milions of ways to do that, but this one is very simple and it works like a charm! Credits to: Matt Mullenweg.

1) Put all of pictures into a specific folder on your web server. They should have extension: jpg, jpeg, png or gif and apropriate dimensions.

2) Copy this code and paste it into Notepad:

<?php
/*
By Matt Mullenweg > http://photomatt.net
Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
Latest version always at:
http://photomatt.net/scripts/randomimage
*/// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';
// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along
header('Location: '.$folder.$files[$rand]); // Voila!
?>


3) Save the document as rotate.php and upload it to the same folder with pictures.

4) In your header or wherever you want to show random pictures, put following line of code to call the rotate.php
<img src="http://www.path to folder with pictures/rotate.php" alt="A Random Image" />

1 comments

  1. digiclay infotech // 12 April 2013 at 15:08  

    Thank you so much for providing plenty of useful content.
    Web Solutions Indore

Take a look on my other postings: