Show random image in PHP
Change $dir to image folder
Copy this code and paste it in your HTML
<?php
Header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
Header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
Header("Content-Type: image/gif");
$dir = "img/backgrounds";
//$imglist = "";
$i = 0;
while(($file = readdir($dh)) !== false){ if($file != '..' && $file != '.'){
$image[$i] = $file;
$i++;
}
}
}
}
if(!readfile($dir."/".$image[$n])) // Read the image readfile($dir."error/error.gif");
// If the script can't find the directory, display this image ?>
Report this snippet
Comments
Subscribe to comments
my solution, think it's better and has extension check
$dir = 'i'; $imgext = array('jpg', 'jpeg', 'gif', 'png'); $images = array(); if($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { $info = pathinfo($dir.'/'.$file); if(inarray($info['extension'], $img_ext)) {
$images[] = $file; } }
}
$random = array_rand($images); echo $images[$random];
my solution, think it's better and has extension check
$dir = 'i'; $imgext = array('jpg', 'jpeg', 'gif', 'png'); $images = array(); if($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { $info = pathinfo($dir.'/'.$file); if(inarray($info['extension'], $img_ext)) {
$images[] = $file; } }
}
$random = array_rand($images); echo $images[$random];