Home > Mobile >  Display a random image from the folder using session with PHP
Display a random image from the folder using session with PHP

Time:01-10

How can I display a random image from the folder using a session with PHP? This is what I have for now but it shows only one specific image:

$images = array("1.jpg", "2.jpg", "3.jpg", "4.jpg","5.jpg");

if(!isset($_SESSION['image'])){
    $_SESSION['image'] = rand(0, count($images));
}

echo "<img src='adv/".$images[1]."'>";

Am I going in the wrong direction to do this?

Thanks for your help

CodePudding user response:

this is becouse you are showing 1 specific image in any way! $images[1] will always returns $images[1] .

you can use such scripts just like this :

if(!isset($_SESSION['image'])){
    $_SESSION['image'] = rand(0, count($images));
}else{
   // let prevent from last image loading too.
   while(in_array(($random = mt_rand(0,count($images))), array($_SESSION['image'])));
   $_SESSION['image'] = $random;
}
echo "<img src='adv/" . $_SESSION['image'] . ".jpg'>";
  •  Tags:  
  • Related