I'm trying to make a site where users can submit photos, and then randomly view others photos one by one on another page. I have a directory called "uploads" where the pictures are submitted. I'm having trouble reading the pictures from the file. I just want to randomly select a picture from the directory uploads and have it displayed on the page. Any suggestions appreciated.
4 Answers
I've turned it a little to get more than one random file from a directory using array.
<?php
function random_pic($dir)
{
$files = glob($dir . '/*.jpg');
$rand_keys = array_rand($files, 3);
return array($files[$rand_keys[0]], $files[$rand_keys[1]], $files[$rand_keys[2]]);
}
// Calling function
list($file_1,$file_2,$file_3)= random_pic("images");
?>
You can also use loop to get values.

- 705
- 10
- 13
-
+1 better than calling random_pic() three times, as this avoids duplicates. (Better still to make the 3 an optional parameter to random_pic().) – Bob Stein Jul 26 '13 at 14:19
This single line of code displays one random image from the target directory.
<img src="/images/image_<?php $random = rand(1,127); echo $random; ?>.png" />
Target directory: /images/
Image prefix: image_
Number of images in directory: 127
https://perishablepress.com/drop-dead-easy-random-images-via-php/
Drawbacks
images must be named sequentially (eg
image_1.png
,image_2.png
,image_3.png
, etc).you need to know how many images are in the directory in advance.
Alternatives
Perhaps there's a simple way to make this work with arbitrary image-names and file-count, so you don't have to rename or count your files.
Untested ideas:
<img src=<?php $dir='/images/'; echo $dir . array_rand(glob($dir . '*.jpg')); ?> />
shuffle()
scanDir()
withrand(1,scanDir.length)

- 2,047
- 7
- 27
- 52
Or you can use opendir() instead of glob() because it's faster
-
1You are probably correct. You should write an implementation that uses the opendir() method, and post it in your answer. – Eric Seastrand Jul 26 '17 at 22:31
-
Seemingly, you cannot. `opendir()` and `glob()` are said to be two different functions. See https://stackoverflow.com/questions/12119304/select-random-file-using-opendir. And `glob()` would be the one to use here; see https://www.w3schools.com/php/func_filesystem_glob.asp. – Frank Conijn - Support Ukraine May 05 '18 at 09:43
-
I obviously meant that it's faster to use the opendir way (opendir, then iterate through the files), not only the opendir function. The link I've included explains what opendir() returns. – May 12 '18 at 07:40