Random image script.

Discussion in 'PHP' started by sittsait, Jul 11, 2008.

  1. #1
    Hi, im currently using:
    <?php
    include_once "maincore.php";
    $folder = 'images/';
    $base = 'http://www.---.--/';
    
    // Space seperated list of extensions, you probably won't have to change this.
    $exts = 'jpg';
    
    $files = array(); $i = -1; // Initialize some variables
    if ('' == $folder) $folder = './';
    
    $handle = opendir($folder);
    $exts = explode(' ', $exts);
    while (false !== ($file = readdir($handle))) {
    foreach($exts as $ext) { // for each extension check the extension
    if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
    $files[] = $file; // it's good
    ++$i;
    }
    }
    }
    closedir($handle); // We're not using it anymore
    mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
    $rand = mt_rand(0, $i); // $i was incremented as we went along
    
    echo "[COLOR="Red"]<a href=$base$folder$files[$rand] target='_blank'>[/COLOR]<img src=\"$base$folder$files[$rand]\" width='157' height='116' border='0'/>";
    ?>
    Code (markup):
    The problematic section is in red. I want the images to be linked name.swf not name.jpg

    Help much appreciated.
     
    sittsait, Jul 11, 2008 IP
  2. JLEville

    JLEville Peon

    Messages:
    147
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    echo "<a href=" . $base . $folder . $files[$rand] . "target='_blank'><img src=\" . $base . $folder . $files[$rand] . "\ width='157' height='116' border='0'/>";
     
    JLEville, Jul 11, 2008 IP
  3. sittsait

    sittsait Guest

    Messages:
    22
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for the quick answer, but your code is not working. If i fixed the syntax / char errors, it did the same: Linked name.JPG insead of name.SWF
     
    sittsait, Jul 11, 2008 IP
  4. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #4
    Completely rewritten code for a desperate stab in the dark ;)

    $dir = './images';
    
    if($dir) chdir($dir);
    $files = glob('*.jpg');
    $file = $files[rand(0,count($files)-1)];
    
    echo "<a href='" . str_replace('.jpg', '.swf', $file) ."' target='_blank'><img src='$file' width='157' height='116' border='0'/>";
    PHP:
     
    Danltn, Jul 11, 2008 IP