NeoArch

February 25, 2006

PHP, CSS, and Random Pictures

Filed under: PHP, Systems, Technology — Jason @ 2:52 am

I found this script at Steven Davies’s website. It was designed to insert a random picture into a page. I tweaked it so that it would output a random background image into an embedded CSS. To use it, copy the code below and save it into your directory as rotate_script.php. Make sure to change the $dir variable to the display the directory in which you keep your images. Then include include a line like background-image: <?php include("rotate_script.php"); ?>; in the midst of the embedded style in the header where you want it to appear.


<?php
/*
# Random Image Generator
# This script will scan a directory of your choosing, ignoring folders and
# the dreaded Thumbs.db file and then return a randum image from the specified
# folder. Easy to customise and use :-) I recommend using include() with this.
#
# This code is free to use and written by Steven Davies. If you do use, please
# leave the comment in a code so other web authors can find this site!
#
# This code was taken from www.phub.co.uk
*/

/* Customise this line to change to your images folder */
$dir = ‘images’;
$dh = opendir($dir);
/* The following loop scans the directory specified ignoring folders and Thumbs.db */
while (false !== ($filename = readdir($dh))) {
if($filename == “Thumbs.db” || is_dir($filename)){
}else{
$files[] = $filename;
}
}

/* Generate a random number */
$nooffildi = count($files);
$nooffiles = ($nooffildi-1);
srand((double)microtime()*1000000);
$randnum = rand(0,$nooffiles);

/* print the result */
echo “url($dir/$files[$randnum])”;
?>

Again, thanks to Steven for his helpful script!

4 Comments »

  1. I will try and tell u….
    But I am searching different think…..
    Like:::
    I have a folder with full of images…
    A php script will generate atleast 20 images each time in a random order. I do not know the image file name. only folder name is know to me. Ok,
    —-
    I can generate a{single} random image from a folder, but not 20 or 30 images..
    If any one know that script please e-mail me at: pankaj_saha at yahoo dot com.
    Thank you.

    Comment by Pankaj Saha — April 6, 2007 @ 11:16 am

  2. Sorry E-mail will be: pankaj_saha83 at yahoo dot com

    Comment by Pankaj Saha — April 6, 2007 @ 11:17 am

  3. Yes it good script

    Comment by ธีม — May 22, 2008 @ 3:57 am

  4. A four boysat each goalpost, erotic sex stories long, before. Dodie had started feeling as.

    Comment by jkexagtu — June 18, 2008 @ 9:08 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.