Hello Angela,

Friday, January 16, 2004, 11:30:16 AM, you wrote:

AKH> <?php
AKH> // images in folder
AKH> $total = "5";

AKH> // file type
AKH> $file_type = ".htm, .gif, .jpg";

AKH> // dir location
AKH> $image_folder = "dir/dir";

AKH> $start = "1";

AKH> $random = mt_rand($start, $total);

AKH> $image_name = $random . $file_type;

AKH> // print file name
AKH> // echo "$image_name";

AKH> // display image
AKH> // echo "<img src=\"$image_folder/$image_name\" alt=\"$image_name\" />";

?>>

AKH> I'd like the code to take the HTML and place it in a <div></div>,
AKH> probably using a <?php require (""); ?> (I think I'm OK with this once
AKH> the code is sorted).  

Your code will produce the following image filename:

5.htm, .gif, .jpg

(assuming the random number you get is 5)

Which probably isn't what you want :)

There are a couple of ways to do this. One of the easiest would be to
assume that you have all "random" images in one specific directory
(called randpics for the sake of the following code). Then your
script can read out a list of files in that directory and pick one at
random and display it. The following should do the trick:

<html>
<head>
        <title>Random Images</title>
</head>

<body>

<?php 
$random_images_directory = "randpics";

if ($handle = opendir($random_images_directory)) {
    while (false !== ($file = readdir($handle))) { 
        if ($file != "." && $file != "..") { 
                        $random_images[] = $file;
        } 
    }
    closedir($handle); 
}

/*
        All of the files in that directory are now in the array $random_images
        so let's pick one to display:
*/

        $image = $random_images[mt_rand(0, count($random_images)-1)];
?>

        <div align=center>
                <img src="randpics/<? echo $image?>" border=0 alt="Random!">
        </div>

</body>
</html>

Caveat: This will only work if you only have image files in the random
images directory. If you had say an mp3 in there, it would try to
display it :) So if this isn't going to be the case then you need to
add a further check into the while loop to check the extension of the
file before adding it to the $random_images array.

count returns the number of values in an array including that held at
location 0, that is why I minus 1 from the count() function when
getting a random image.

Sorry that this doesn't actually use your original script, but this
way is a lot less maintenance - you can just upload a whole bunch of
new images into the folder and the script will see them automatically
without needing to mess with a $total variable.

-- 
Best regards,
 Richard                            mailto:[EMAIL PROTECTED]

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to