SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Addict
    Join Date
    Jul 2005
    Posts
    215
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Random Image Every 10 Seconds

    HI All,
    I need help with reloading Random Image every 10 seconds. Following are the code that I have which loads Random Image from the Directory (this part is working fine), when I refresh the page. But now I want change it so it would reload random image every 10 seconds. Any help will be appriciaged.

    PHP Code:
    <? 
    function randomImage($number,$dir) {
       
    $read '../Project/xRand_Img/';    
       
    $myDirectory opendir($read);    
          while(
    $entryName readdir($myDirectory)) { 
              if (
    strtolower(substr($entryName, -3)) == "jpg") { 
                 
    $dirArray[]=$entryName;
              } 
           } 
        
    closedir($myDirectory);
        
        for(
    $i=0;$i<$number;$i++) {
            
    $numImg sizeof($dirArray); 
            
    $numRan rand(0,$numImg); 

            
    $img '<img src=' .$dir.$dirArray[$numRan]. '>';
        }

        return 
    $img;

        
    echo 
    randomImage(1,'../Project/xRand_Img/'); 
    ?>

  2. #2
    SitePoint Guru hisham777's Avatar
    Join Date
    Dec 2005
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    this is a dublicated thread its against the rules.

    your Q

    PHP is a server side script which get exicuted in the server then send its output
    to the client.

    your solution is to use Java Script, its a client side Script.

    may be you can use both to get the result you want.

    i hope it helps

  3. #3
    Evil Genius MilchstrabeStern's Avatar
    Join Date
    Nov 2003
    Location
    Arizona
    Posts
    1,131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I agree, you would probably want to use javascript.

    However, could you not use some function to loop constnatly, and wait 10 seconds between the loops?
    ]

  4. #4
    SitePoint Addict
    Join Date
    Jul 2005
    Posts
    215
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hisham777 Wrote: this is a dublicated thread its against the rules
    I posted this Post twice by mistake.

    From your response, it appears that I would be better of using JavaScript for this process. Thanks.

  5. #5
    Keep it simple, stupid! bokehman's Avatar
    Join Date
    Jul 2005
    Posts
    1,935
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's a demo! Here's the script:
    PHP Code:
    <?php
    // PHP section

    // set some variables
    // Image directory! fill in! relative to root
    $imageDir '/slides/'
    define('SERVERPATH'$_SERVER['DOCUMENT_ROOT'].$imageDir);
    define('HTTPPATH''http://'.$_SERVER['HTTP_HOST'].$imageDir);

    // read the names of images from the image directory
    $dir opendir(SERVERPATH);
    $javascriptArray null;
    $i null;
    while (
    false !== ($file readdir($dir))) {
        if (
    eregi('\.(gif|png|jpg)$'$file)){
            
    $javascriptArray .= $i.'"'.HTTPPATH.$file.'"'
            
    $i ',';
        }
    }
    closedir($dir);

    // Html section
    ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

    <html lang="en">
        <head>
            <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
            <title>Rotate Images</title>
            <script type="text/javascript">
                rotatingImages = new Array(<?php echo $javascriptArray?>);
                imageCount = rotatingImages.length;
                firstTime = true;
                duration = "3"; //seconds
            
                function rotateImage(){
                    // Cycle through images sequencially starting with a random image
                    // Do not update the image if loading is not yet completed
                    if (document.getElementById('rotatingImage').complete || firstTime){
                        if (firstTime) {
                            thisImage = Math.floor((Math.random() * imageCount))
                            firstTime = false
                        }else{
                            thisImage++
                            if (thisImage == imageCount) {
                                thisImage = 0
                            }
                        }
                        document.getElementById('rotatingImage').src = rotatingImages[thisImage]
                        setTimeout("rotateImage()", duration * 1000)
                    }
                }
            </script>
            <style type="text/css">
                #slideshow{
                    width:164px;
                    height:124px;
                    border-top:2px solid #997;
                    border-right:2px solid #997;
                    border-bottom:2px solid #664;
                    border-left:2px solid #664;
                }
                
                #rotatingImage{
                    display:block;
                    width:160px;
                    height:120px;
                    border-top:2px solid #664;
                    border-right:2px solid #664;
                    border-bottom:2px solid #997;
                    border-left:2px solid #997;
                }
            </style>
        </head>
        <body>
            <div id="slideshow">
                <img id="rotatingImage" src="" alt="">
            </div>
            <script type="text/javascript">
                rotateImage();
            </script>
        </body>
    </html>
    It reads all the images in a directory and then uses javascript to run them as a slide show. It starts on a random image from the javascript array and then rotates from there. If you want to randomise the order you could use PHP's shuffle(). You could make it more responsive by preloading the images.

  6. #6
    SitePoint Addict
    Join Date
    Jul 2005
    Posts
    215
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Bokehman,

    Thats exactly what I was looking for, I can use that for Banner Rotation purpose. That helps a lot. Thank you.

  7. #7
    Are You There? KDesigns's Avatar
    Join Date
    Oct 2003
    Location
    Your Monitor
    Posts
    1,146
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Another method you may want to try is by creating a flash movie for the slideshow that then uses flash's ability to get variables from an external file. Javascript is probably the best route, but it's another way.
    ChooseDaily.com - Follow on Twitter
    Top Resources for Web Designers and Developers Every Day!

  8. #8
    SitePoint Member
    Join Date
    Jun 2010
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    bokehman I have copied the script that you wrote, can you please tell me where the destination path goes in the script? Thanks

  9. #9
    SitePoint Member
    Join Date
    Dec 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Cool

    Quote Originally Posted by bokehman View Post
    Here's a demo! Here's the script:
    PHP Code:
    <?php
    // PHP section

    // set some variables
    // Image directory! fill in! relative to root
    $imageDir '/slides/'
    define('SERVERPATH'$_SERVER['DOCUMENT_ROOT'].$imageDir);
    define('HTTPPATH''http://'.$_SERVER['HTTP_HOST'].$imageDir);

    // read the names of images from the image directory
    $dir opendir(SERVERPATH);
    $javascriptArray null;
    $i null;
    while (
    false !== ($file readdir($dir))) {
        if (
    eregi('\.(gif|png|jpg)$'$file)){
            
    $javascriptArray .= $i.'"'.HTTPPATH.$file.'"'
            
    $i ',';
        }
    }
    closedir($dir);

    // Html section
    ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

    <html lang="en">
        <head>
            <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
            <title>Rotate Images</title>
            <script type="text/javascript">
                rotatingImages = new Array(<?php echo $javascriptArray?>);
                imageCount = rotatingImages.length;
                firstTime = true;
                duration = "3"; //seconds
            
                function rotateImage(){
                    // Cycle through images sequencially starting with a random image
                    // Do not update the image if loading is not yet completed
                    if (document.getElementById('rotatingImage').complete || firstTime){
                        if (firstTime) {
                            thisImage = Math.floor((Math.random() * imageCount))
                            firstTime = false
                        }else{
                            thisImage++
                            if (thisImage == imageCount) {
                                thisImage = 0
                            }
                        }
                        document.getElementById('rotatingImage').src = rotatingImages[thisImage]
                        setTimeout("rotateImage()", duration * 1000)
                    }
                }
            </script>
            <style type="text/css">
                #slideshow{
                    width:164px;
                    height:124px;
                    border-top:2px solid #997;
                    border-right:2px solid #997;
                    border-bottom:2px solid #664;
                    border-left:2px solid #664;
                }
                
                #rotatingImage{
                    display:block;
                    width:160px;
                    height:120px;
                    border-top:2px solid #664;
                    border-right:2px solid #664;
                    border-bottom:2px solid #997;
                    border-left:2px solid #997;
                }
            </style>
        </head>
        <body>
            <div id="slideshow">
                <img id="rotatingImage" src="" alt="">
            </div>
            <script type="text/javascript">
                rotateImage();
            </script>
        </body>
    </html>
    It reads all the images in a directory and then uses javascript to run them as a slide show. It starts on a random image from the javascript array and then rotates from there. If you want to randomise the order you could use PHP's shuffle(). You could make it more responsive by preloading the images.
    Hi guys

    for some reason i receive an error taht leads me to this line of code"
    define('SERVERPATH', $_SERVER['DOCUMENT_ROOT'].$imageDir);

    All it does is echos out an error:
    warning readdir() expects parameter 1 to be resource .. blah blah.php line 15

    I dont know why that is and have googled the error to find that google tries to correct my spelling, it suggests 'SERVER_PATH' .. is it because im running windows 7 Ultimate on my localhost using XAMPP as my php server ?

    The dir is c:\XAMPP\htdocs\rotate\index.php
    and in my browser it is
    http://localhost/rotate/index.php

    thanks for any responses to this
    Michael

  10. #10
    Keep it simple, stupid! bokehman's Avatar
    Join Date
    Jul 2005
    Posts
    1,935
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The directory needs to exist and be readable.

  11. #11
    SitePoint Member
    Join Date
    Dec 2010
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Bokeham

    Thanx for the reply, much appreciated, i did how ever figure it out it was the path like you said lol.
    I took the part of your directory script and used some other code i have to get the result i needed.

    Images fade through to next image, form directory on web server, with image upload in admin side. very nice must admit

    If i wanted to say fill the java array with data from mysql i could replace the directory portion to connect to mysql and select image names from table ... like ... "select from imgtable where imges are not null or equal to nothing" then use that result to populate the array in java like you did with directory via php.

  12. #12
    SitePoint Guru team1504's Avatar
    Join Date
    May 2010
    Location
    Okemos, Michigan, USA
    Posts
    732
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I have been looking for a way to do this for a while.
    Thank you very much!

  13. #13
    SitePoint Member
    Join Date
    Feb 2011
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Bokehman -

    Thanks for the script. It's a great way to ensure the images don't repeat, but rotate through the entire folder.

    Do you know of a way to add links to each photo that would come up? I have about 15 photos that each link to a different page that I need to have rotate every 10 seconds. Your script works beautifully except I don't know how to associate the links to the pictures. Would a table in a database be a better solution?

    Any help is much appreciated.

  14. #14
    SitePoint Enthusiast
    Join Date
    Nov 2009
    Posts
    83
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The Bokehman script is clean and concise. Nicely-done.
    But that method does create a text-based list of image paths on the client, as input to the javascript. If you want to loop over a large image collection View-Source gets ugly. And it would dramatically increase page download time.

    You can create a list as a _SESSION variable on the server, and then use ajax
    to request one image name at a time:

    slideshow.php

    and

    nextimage.php


    demo


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •