I want a web page to display several random images on load. I've th开发者_运维技巧ought of several solutions but I would really like to be able to dump images into a folder without renaming them, and the web page will choose from those images in the folder and display them
I can imagine a PHP solution that will display random images from a folder, but it will need to look for certain names.
So my next step was to have an SQL database where every image got a key, and 10 keys would be chosen random by a query - the images associated with them would then be passed into an array that the document will load the elements of.
But now I guess I need to know how to automatically populate an SQL database by having it read a folder?
Insight appreciated, if I don't have to reinvent the wheel the better
Glob works like on the filesystem, e.g. supports wildcards
$files = glob('/path/to/files/*.jpg');
$yourRandomFile = array_rand($files);
This will return a random JPG file, based on it's extension.
This should do it :
function your_dir ($directory)
{
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$results[] = $file;
//or sql query for each file
$sql = mysql_query("SELECT * FROM your_table WHERE your_file = '".$file."'");
if(mysql_num_rows !== 0){
//your query...
}
//
}
}
closedir($handler);
return $results;
}
$directory = '/path/to/your/directory';
your_dir($directory);
Would probably be better to select existing files from db first put them into an array and exclude them rather than checking for each one.
You can do as below.
1. read complete dir from where you want the page to load the image
2. store the image names in array
3. now generate a number using random function from 1 to size of the array
4. consider the generated number as key for the array and use that image name to put the image.
精彩评论