How to display randomly selected images inside a div?
Question
I'm trying to display two randomly selected images from a dir
Instead of images, img.names are displayed
$dir = 'memb_area/captcha/imgs/';
$files = scandir($dir);
$rand_keys = array_rand($files, 2);
echo $files[$rand_keys[0]] . "\n";
echo $files[$rand_keys[1]] . "\n";
Also tried:
echo '<img src="memb_area/captcha/imgs">' + 'echo $files[$rand_keys[0]] . "\n";'
And - is it possible to print these pictures inside a separate div on a page?
Solution
+
is not a valid PHP concatenation character. .
is. By using +
, you are effectively adding these two strings, which when converted to integers, equate to 0
.
This line:
echo '<img src="memb_area/captcha/imgs">' + 'echo $files[$rand_keys[0]] . "\n";'
should be:(updated)
echo "<img src=\"memb_area/captcha/imgs/".$files[$rand_keys[0]]."\">".PHP_EOL;
Update 01: (OP's Comment: but after refreshing, after two or three times - nothing is displayed. Next refresh - image is displayed... and so on.)
Scandir php.net (Example #1) says that:
Array
(
[0] => .
[1] => ..
[2] => bar.php
[3] => foo.txt
[4] => somedir
)
So, maybe your scandir($foo)
is returning an array with two keys having invisible directories as their values.
Try this code and let me know:
$dir = 'memb_area/captcha/imgs/';
$files = scandir($dir);
if($files[0] == ".") unset($files[0]);
if($files[1] == "..") unset($files[1]);
$files = array_values($files); // reset array keys back to 0,1,2..
$rand_keys = array_rand($files, 2);
echo $files[$rand_keys[0]] . "\n";
echo $files[$rand_keys[1]] . "\n";
echo "<img src=\"memb_area/captcha/imgs/".$files[$rand_keys[0]]."\">".PHP_EOL;
OTHER TIPS
I think there might be error in path.
try this: echo '<img src="memb_area/captcha/imgs/">' + 'echo $files[$rand_keys[0]] . "\n";'