467,877 Members | 1,149 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,877 developers. It's quick & easy.

random rotating image banner from folder source

Hi, I'm still kinda new to PHP so I could do with some advice. I'm using the code below to select and show a random image from a folder of images.

rotate.php
[PHP]<?php

// 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!
?>[/PHP]


The file is called as a standard image link: <img src="rotate.php">
What I'd like to do is have the image change after time limit and/or have a HTML link that will force an image change. I've seen similar stuff, but I like the idea that I can just add a new image to the folder and it will automatically be used without any code change.

The problems are as follows:
I can't add to the HTML source, with the exception creating the link and image source (long story, I'm using it on a blog!). I can upload more source files etc. if needs be.

Anyone who can suggest a solution, I'd greatly appreciate it.

Cheers!
Mar 21 '07 #1
  • viewed: 2201
Share:
1 Reply
code green
Expert 1GB
There are a couple of ways of doing this. I store the file address of my rotating banners in a mysql database and select them randomly with a preferential weight..
But if you want to stick to files only then load the file address within your loop into an array then use array_rand();
Mar 22 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Ian Hubling | last post: by
1 post views Thread by Sandy Bremmer | last post: by
4 posts views Thread by tshad | last post: by
10 posts views Thread by Joey_Stacks | last post: by
1 post views Thread by kennykenn | last post: by
5 posts views Thread by rodmc | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.