How to Display Random Image from Folder in PHP

This is a quick tutorial about displaying random image from folder in php. It will be useful if you want to include featured section area on websites. And all these images will come from a folder and rotated through at regular time interval. A random image will be picked up from the lot one at a time and displayed here.

PHP Code

<?php
    $dir_path = "images";
    $files = scandir($dir_path);
    $count = count($files);
    $index = rand(2, ($count-1));
    $filename = $files[$index];
    echo '<img src="'.$dir_path."/".$filename.'" alt="'.$filename.'">';    
?>

Leave a Reply

Your email address will not be published. Required fields are marked *