|
Posted by J.O. Aho on 03/03/07 20:06
Fred Atkinson wrote:
> I need a PHP script that can be invoked refererencing a
> subdirectory where thumbnails are stored and have it randomly display
> one of those thumbnails.
>
> To expand upon my needs, here is the hierarchy of the Web
> site:
>
> main pages public_html
>
> subpages apple banana coconut
>
> sub-subpages aa bb cc dd ee ff gg
>
> Each of the aa-gg subdirectories will contain thumbnail .jpg
> files. I'd like to be able to invoke the script quite a few times
> within the same PHP page.
> From the page in /banana, use <?php random_image $dir=aa> to
> return a thumbnail that it randomly took from sub page /banana/aa. I
> would invoke a thumbnail from another directory by changing aa to bb,
> cc, dd, ee, ff, or gg.
Make a file that you can include in your pages
--- randomimg.php ---
class randomimg {
protected $imgs=array();
protected $basepath;
function randomimg($base='.') {
$this->basepath=$base;
}
function getimg($path) {
if(empty($this->imgs[$path])) {
$this->imgs[$path]=scandir($this->basepath.'/'.$path);
}
/* Older versions need srand to work */
$version=explode('.',phpversion());
if((intval($version[0])<4) || ((intval($version[0])==4) &&
(intval($version[1])<2))) {
/* We have PHP 4.1 or older, so we need srand() to get random
numbers */
list($usec, $sec) = explode(' ', microtime());
srand((float) $sec + ((float) $usec * 100000));
}
return $path.'/'.$this->imgs[$path][rand(0,count($this->imgs[$path])-1)];
}
}
--- eof ---
> From the page in /banana, use <?php random_image $dir=aa> to
> return a thumbnail that it randomly took from sub page /banana/aa. I
> would invoke a thumbnail from another directory by changing aa to bb,
> cc, dd, ee, ff, or gg.
in the page where you need the random images:
--- subpages.php ---
include_once('randomimg.php')
$images= new randomimg();
$path_to_the_image=$images->getimg('aa');
--- eof ---
--- main_pages.php ---
include_once('randomimg.php')
$images= new randomimg();
$path_to_the_image=$images->getimg('coconut/bb');
--- eof ---
It will just read a directory once, store all the files/directories in an
array and if the same directory is used more than once, it will skip the part
of scanning the directory.
Of course, I would most likely used a database for the file names/paths,
classes and so on.
--
//Aho
Navigation:
[Reply to this message]
|