Forum Moderators: coopster

Message Too Old, No Replies

Skip missing random image.

Random image and random caption.

         

D_Blackwell

6:21 am on Nov 11, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This was recommended as way to skip an image that does not exist. However, it is not working and displays the page without an image. I want it to skip to a valid image if a typ0 in the file name for example. It seems to be missing what to do if the file does not exist?

if (file_exists($selectedImage) && is_readable($selectedImage)) {
$imageSize = getimagesize($selectedImage);
}
........................

I have a quote that goes with each image:

$images = array (
array ('file' => 'butterfly',
'caption' => 'text'),
array ('file' => 'stick',
'caption' => 'text'),
),
);
$i = rand (0, count($images) -1);
$selectedImage = "images/{$images[$i]['file']}.jpg";
$caption = $images[$i]['caption'];

but want to randomize the quote selection as well. Not having any luck at finding a sample that randomizes both selections or creating on my own. I assume that I will have to change the associative array structure, but will also need to use $i to select from both arrays as needed.

rocknbil

8:11 pm on Nov 11, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Reading your post kinda "backwards"

$selectedImage = "images/{$images[$i]['file']}.jpg";

if (file_exists($selectedImage) && is_readable($selectedImage))....

maybe you need to use a full system path?

$imgURL = "/images/{$images[$i]['file']}.jpg";
$imgPath = "/full/system/path/{$images[$i]['file']}.jpg";
if (file_exists($imgPath) && is_readable($imgPath))...

Or does the file really not exist? Note the addition of the forward slash for the url, your PHP may be in document root but in case some condition has reset the base href or you need to access the function from some other directory, this insures it will always find /images from the browser.

The simplest solution I'd guess is when you build your array, build it only of existing files. You'd still want to check that they exist at that point, but it's a good place to collect all the image data (w,h,src,alt,captions) and store them in a multidimensional array or an object.

To keep track of the associations (as in your captions, but following the above, for other attributes as well) as mentioned, use a multidimensional array and extract the keys from the array. Then you just need to do your rand on the keys themselves.