Load random images from folder in Php



This tutorial will go over how to pull any image from a specified folder, store path in an array and display random image on a page.

Step 1:-
//Specify path to search images from directory
$dir = 'images/';

Step 2:-
//scan directory content using scandir() function
$filesscandir($dir);

Step 3:-
//take random value from array
$random_index = array_rand($files);

Step 4:- 
finally display image
echo "<img src=" .$dir . $files[$random_index] . ">";


But when you display images some times it displays some hidden files. you can check contents of array by using print_r() command.
==> print_r($files);
it will show output as follows.
==> Array ( [0] => . [1] => .. [2] => HHRCK.png [3] => dsgsdg.jpg 

I don't have enough rep to explain about this dots. This tradition comes from the Unix world. I guess it is because it allows you to quickly see the permissions for the current and parent directories on each call of ls.

. refers to the current directory .. refers to the parent directory.


You will have to filter them out manually.

As of PHP 5.3 there is the FilesystemIterator which extends the DirectoryIterator and skips dot-files by default. 
here i used another array with the value [ '.' , '..']
and then find the difference between two arrays

So final code is as follows

<?php
$dir = 'images/';
$files =array_diff(scandir($dir), array('..', '.'));
$random_index = array_rand($files);
echo "<img src=" .$dir . $files[$random_index] . ">";
?>


whenever you refresh page random images will display.

0 comments :