err... i think i misdelivered my idea keith.
what i meant by listing all files manually in a flat file and then choosing a random image from it. should be listing all images files in a flat file through such mechanism and then choosing a random image from it.
The function of flat file here is as "cache". The existence of flat file will reduce time wasting while reading directory and generating seed. This process could be called automatic, since you don't write all filenames by yourself. You may also involve cron job to update the image file list in the file.
Here is an example code of how it works:
PHP Code:
//Set up variables
$imgDir = "myImage/"; //relative to current file
$imgListFile = "imglist.txt";
function fileExtension ($givenFile) {
$arrayFile = explode(".",$givenFile);
$ext = count($arrayFile) - 1;
return $arrayFile[$ext];
}
function file_list($dir) {
global $imgListFile;
if (is_dir($dir)) {
$fd = @opendir($dir);
while (($part = @readdir($fd)) == true) {
if ($part != "." && $part != "..") {
if(is_file($dir.$part)) {
if (fileExtension($part) == "jpg" || fileExtension($part) == "jpeg" || fileExtension($part) == "gif" || fileExtension($part) == "png") {
$file_array[] = $part;
}
}
}
clearstatcache();
}
if ($fd == true) {
closedir($fd);
}
if (is_array($file_array)) {
natsort($file_array);
$fp = fopen($imgListFile,'wb');
if(is_writable($imgListFile) && flock($fp,LOCK_EX)) {
for($i=0;$i<count($file_array); $i++)
$content .= $file_array[$i].";";
$content = preg_replace("/;$/","\n",$content);
fwrite($fp,$content);
flock($fp,LOCK_UN);
fclose($fp);
}
return $file_array;
}
else {
return false;
}
}
else {
return false;
}
}
function imgFromFile ($pathToFile) {
$fp = fopen($pathToFile,'rb');
if(!$fp)
return 0;
$fileImg = fread($fp,filesize($pathToFile));
fclose($fp);
$file_array = explode(";",$fileImg);
return $file_array;
}
function chooseImg($method = 1) {
if($method == 1) { //use file_list
global $imgDir;
$fileList = file_list($imgDir);
}
else { //use imgFromFile
global $imgListFile;
$fileList = imgFromFile($imgListFile);
}
$totElement = count($fileList) - 1;
$chosen = rand(1,$totElement);
return $fileList[$chosen];
}
//Usage:
$img = chooseImg(1);
print "Image chosen from <b>listing image file</b>: ".$img;
print "<br />";
$img = chooseImg(2);
print "Image chosen from <b>$imgListFile</b>: ".$img;
This code does run. When I made it, I'd tested it with dummy data. This is a special one for you!! Wish this help..
Bookmarks