Displaying random image using php

Discussion in 'PHP' started by derek34, Dec 17, 2007.

  1. #1
    Hi
    I am building a website and I want to display a random image every time the page is refreshed. Since I know php, I figured it would be easiest to do it using that language. Does anyone know how to do this?
    Thanks
    - Derek
     
    derek34, Dec 17, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    <?php
    
    $images = array(
        'image1.jpg',
        'image2.jpg',
        '...'
    );
    
    header('Content-Type: image/jpeg');
    readfile($images[array_rand($images)]);
    
    ?>
    
    PHP:
     
    nico_swd, Dec 17, 2007 IP
  3. derek34

    derek34 Guest

    Messages:
    34
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    so I would just embed that code into my HTML?
    wouldn't I have to use a <img src "" /> tag?
     
    derek34, Dec 17, 2007 IP
  4. sunnyverma1984

    sunnyverma1984 Well-Known Member

    Messages:
    342
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    120
    #4
    lets you have images at same folder where php file
    img1
    img2
    img3
    .
    .
    .
    img50
    <img src="img<? echo rand(1,50); ?>" >
    PHP:
     
    sunnyverma1984, Dec 17, 2007 IP
  5. Brewster

    Brewster Active Member

    Messages:
    489
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    60
    #5
    Copy the code that nico has given you into a file called image.php and call it from you html document using <img src="image.php" />

    Brew
     
    Brewster, Dec 17, 2007 IP
  6. derek34

    derek34 Guest

    Messages:
    34
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #6
    alright thanks guys. I'll let you know if it works...
     
    derek34, Dec 17, 2007 IP
  7. jmiil

    jmiil Member

    Messages:
    35
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #7
    It works.

    
    $images = array(
        'http://www.website.com/image1.jpg',
        'http://www.website.com/image2.jpg',
        '...'
    );
    echo'<img src="'.$images[array_rand($images)]).'">';
    
    Code (markup):
     
    jmiil, Dec 17, 2007 IP