简体   繁体   中英

How can I display a random image on a web-page for 2 minutes, then change images?

I have a small php script that is supposed to display a random image from a folder then change images every 2 minutes. The problem I'm running into is every so often, we get an error:

NOT FOUND

ERROR: could not connect to http://somedomain.com/TV/imgSlider.php

Here is the script I'm using to pick a random image(out of a folder called quotes ) to display, and refresh the page every 120 seconds(Using meta refresh):

<?php
    $dirContents = scandir('quotes');
    // Unset the ".." and "." that are included in the array returned by scandir()
    unset($dirContents[0]);
    unset($dirContents[1]);

?>
<html>
    <body bgcolor="black">
    <?php
        // Grab random index for the array then grab the image name and push it into
        // the <img> tag.
        $randImgIndex = array_rand($dirContents);
        $randImg = $dirContents[$randImgIndex];
        echo "<img src=\"quotes/$randImg\" style=\"width:100%;height:100%\">";
    ?>
    </body>
<meta http-equiv="refresh" content="120">
</html>

Is there a reason why this script would throw that type of error(or why the script might not be accessible)? Anything I can do to prevent this error? Any other methods of doing this that might help?

Thanks!

If you are interested in trying it with Jquery, personally i think it is a cleaner way then php for this process then try something like below:

 <script> 
  function changeImg(min, max) { // create the function for changing the images
        var noi = max - min; // number of images
        var numRand = Math.floor(Math.random() * noi) + min; // randomized number
        $("#banner").find("img").attr('src','pages/gallery/PhotoWall/images/' + ""+ numRand +"" + '.jpg'); // set a new image
    }

    $(function() { // Waiting for the DOM ready
        setInterval(function(){ // create an interval (loop)
        changeImg(101, 120); // the function with paramteters
        },1000); // the interval in millisecondes --> 1000 = 1 second
    });
</script>

Sourced from: https://forum.jquery.com/topic/getting-a-random-picture-to-display

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM