Thursday, May 21, 2015

Get an image randomly from a directory and display it using PHP and jQuery

Here is how you can get an image randomly from a directory and display it in a webpage using PHP and jQuery:

1. getimage.php:

<?php
    $files = glob('/path-to-dir/*.*');
    $file = array_rand($files);
    echo $files[$file];
?>


and call that script with jquery AJAX :

2. index.html:

<div id="my-img">
</div>
<script>
function get_random_image() {
   $.ajax({
      url: 'getimage.php'
      }).done(function( filename ) {
           jQuery('#my-img').css('background', 'url('+filename+')');
     });
}
setInterval(get_random_image, 5000);
</script>

The background will be replaced by a random image from /path-to-dir/ directory every 5 seconds.