random rotating image banner from folder source

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sunshine192
    New Member
    • Mar 2007
    • 1

    #1

    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($handl e); // We're not using it anymore
    mt_srand((doubl e)microtime()*1 000000); // seed for PHP < 4.2
    $rand = mt_rand(0, $i); // $i was incremented as we went along

    header('Locatio n: '.$folder.$file s[$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!
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    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();

    Comment

    Working...