Load random images within a session
This function returns the path to a random image. In addition it won’t allow the same
image to be loaded repeatedly in a single re-load. ( view demo )
<?php
ob_start();
function session_random_img($min, $max) {
session_name('rand_img');
session_start();
// setting
$path = 'images';
$file_prefix = 'background_';
$extension = '.jpg';
// first run
if (empty($_SESSION['rand_img'])):
$_SESSION['rand_img'] = mt_rand($min, $max);
$output = $_SESSION['rand_img'];
else:
// second run
$i = $_SESSION['rand_img']; // retrieve the already existing value
$k = mt_rand($min, $max);
if ($k == $i) {
while ($i == $k) {
$k = mt_rand($min, $max);
if ($k != $i) { // as soon as $k is != than $i break while loop
break;
}
}
}
$_SESSION['rand_img'] = $k;
$output = $_SESSION['rand_img'];
endif;
$return_output = $path . '/' . $file_prefix . $output . $extension;
return $return_output;
ob_end_flush();
}
?>
<html>
<img src="<?php echo session_random_img(1, 5);?>" />
</html>