Displaying a random image is very easy. All you need is a list of available images, which you store in an indexed array. Since indexed arrays are numbered from 0, you can select one of the images by generating a random number between 0and one less than the length of the array. All accomplished in a few lines of code . . .
Assuming images are already in the images folder.
Assuming you have created include folder
1. Create a blank PHP page in the includes folder and name it random_image.php.
Insert the following code:
<?php
$images = array('kinkakuji', 'maiko', 'maiko_phone', 'monk',
'fountains', 'ryoanji', 'menu', 'basin');
$i = rand(0, count($images)-1);
$selectedImage = "images/{$images[$i]}.jpg";
?>
This is the complete script: an array of image names minus the .jpg filename
extension (there’s no need to repeat shared information—they’re all JPEG), a random
number generator, and a string that builds the correct pathname for the
selected file.Here we use function rand() to generate the random number between the selected images count to display the image randomly. So every time you refresh your browser Every time you change the $images array,you need to count how many elements it contains and change the maximum
The random number is used in the final line to build the correct pathname for the
selected file. The variable $images[$i] is embedded in a double-quoted string
with no whitespace separating it from surrounding characters, so it’s enclosed in
curly braces. Arrays start at 0, so if the random number is 1, $selectedImage is
images/maiko.jpg.
2. Open index.php and include random_image.php by inserting the command in the
same code block as title.inc.php like this:
<?php include('includes/title.inc.php');
include('includes/random_image.php'); ?>
Since random_image.php doesn’t send any direct output to the browser, it’s quite
safe to put it above the DOCTYPE without forcing browsers into quirks mode.
3. Scroll down inside index.php and locate the code that displays the image in the
maincontent <div>. It looks like this:
<div id="pictureWrapper">
<img src="images/basin.jpg" alt="Water basin at Ryoanji temple" width="350" height="237" class="picBorder" />
</div>
4. Instead of using images/basin.jpg as a fixed image, replace it with $selectedImage. All the images have different dimensions, so delete the width and height attributes, and use a generic alt attribute. The code in step 3 should now look like this:
<div id="pictureWrapper">
<img src="<?php echo $selectedImage; ?>" alt="Random image" class="picBorder" />
</div>
5. Save both random_image.php and index.php, and load index.php into a browser.
The image should now be chosen at random. Click the Reload button in your
browser, and you should see a variety of images,
Adding a Caption to the image:
arrays can hold any type of data, including other arrays. To store more than one piece of information about an image, each image in the original $images array needs to be represented by a separate array. Each subarray has two elements: the filename and a caption.
This PHP solution builds on the previous one, so continue working with the same files.
1. Open random_image.php and change the code like this:
<?php
$images = array(
array('file' => 'kinkakuji',
'caption' => 'The Golden Pavilion in Kyoto'),
array('file' => 'maiko',
'caption' => 'Maiko—trainee geishas in Kyoto'),
array('file' => 'maiko_phone',
'caption' => 'Every maiko should have one—a mobile,
of course'),
array('file' => 'monk',
'caption' => 'Monk begging for alms in Kyoto'),
array('file' => 'fountains',
'caption' => 'Fountains in central Tokyo'),
array('file' => 'ryoanji',
'caption' => 'Autumn leaves at Ryoanji temple, Kyoto'),
array('file' => 'menu',
'caption' => 'Menu outside restaurant in Pontocho, Kyoto'),
array('file' => 'basin',
'caption' => 'Water basin at Ryoanji temple, Kyoto')
);
$i = rand(0, count($images)-1);
$selectedImage = "images/{$images[$i]['file']}.jpg";
$caption = $images[$i]['caption'];
?>
it’s an ordinary indexed array that contains eight items, each of which is an associative array containing definitions for 'file' and 'caption'. The definition of the multidimensional array forms a single statement, so there are no semicolons until
end.All the array elements in between are separated by commas. The deep indenting isn’t necessary, but it makes the code a lot easier to read.
The variable used to select the image also needs to be changed, because
$images[$i] no longer contains a string, but an array. To get the correct filename
for the image, you need to use $images[$i]['file']. The caption for the selected
image is contained in $images[$i]['caption'] and stored in a shorter variable.
2. You now need to amend the code in index.php to display the caption like this:
<div id="pictureWrapper">
<img src="<?php echo $selectedImage; ?>" alt="Random image" class="picBorder" />
<p id="caption"><?php echo $caption; ?></p>
</div>
3. Add the following code to random_image.php just before the closing PHP tag:
if (file_exists($selectedImage) && is_readable($selectedImage)) {
$imageSize = getimagesize($selectedImage);
}
The if statement uses two functions, file_exists() and is_readable(), to make
sure $selectedImage not only exists, but also that it’s accessible (it may be corrupted or have the wrong permissions). These functions return Boolean values
(true or false), so they can be used directly as part of the conditional statement.
The single line inside the if statement uses the function getimagesize() to get the
image’s dimensions. The function returns an array containing four elements. By
assigning the result to $imageSize, you can extract the following information:
$imageSize[0]: The width of the image in pixels
$imageSize[1]: The height of the image in pixels
$imageSize[2]: A number indicating the type of file (see Chapter 8 for details)
$imageSize[3]: A string containing the height and width for use in an <img> tag
4. Finally let’s fix the code in step 2. Change it like this:
<div id="pictureWrapper">
<img src="<?php echo $selectedImage; ?>" alt="Random image" class="picBorder" <?php echo $imageSize[3]; ?> />
<p id="caption"><?php echo $caption; ?></p>
</div>
5. Although this sets the dimensions for the image, you still need to control the width of the caption. You can’t use PHP inside an external stylesheet, but there’s nothing stopping you from creating a style block in the <head> of index.php. Put this code just before the closing </hea> tag:
<?php
if (isset($imageSize)) {
?>
<style type="text/css">
p#caption {
width: <?php echo $imageSize[0]; ?>px;
}
</styl>
<?php } ?>
9. The conditional statement at the foot of random_image.php sets $imageSize only if
the selected image both exists and is readable, so if $imageSize has been set, you
know it’s all systems go. Add the opening and closing blocks of a conditional statement around the <div> that displays the image in index.php like this:
<?php if (isset($imageSize)) { ?>
<div id="pictureWrapper">
<img src="<?php echo $selectedImage; ?>" alt="Random image"
class="picBorder" <?php echo $imageSize[3]; ?> />
<p id="caption"><?php echo $caption; ?>
<?php } ?>
Images that exist will display normally, but you’ll avoid any embarrassing error messages in case of a missing or corrupt file—a much more professional look.
Note: When you are using include function better to provide condition before including the page like
$file = 'includes/randomimage.php'
if (file_exists($file) && is_readable($file)) {
include($file);
}
0 comments:
Post a Comment