Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading files in a directory for a slideshow.

Status
Not open for further replies.

Chelsea7

Programmer
Aug 25, 2008
69
US
Hello,

I have a brief question. I'm looking to have php read and display the images from the a folder named images on a webpage. In other words, have each picture appear as a slide show, one at a time. For what I'm gathering , a for loop type statement is required.

Any assistance will be appreciated.
 
Opendir
followed by readdir
followed by validating that the file is an image
followed by deriving the URL for each image
followed by outputting <img> tags for each limits.

There will be examples in the php manual under readdir or opendir most likely.
 
Okay this is what I have below. I can get it to select an image randomally. But I want it to appear on the page on at a time like an automated slideshow;

<?php


$imageDirectory = "/upload/";


$dirHandle = opendir($_SERVER['DOCUMENT_ROOT'].$imageDirectory);


while (false !== ($dirFile = readdir($dirHandle)))
{

if ($dirFile != "." && $dirFile != "..")
{

$randomFile[] = $dirFile;
}
}


echo "<img src=\"".$imageDirectory.$randomFile[rand(0,count($randomFile)-1)]."\" alt=\"Random Image\">\n";


closedir($dirHandle);

?>

Any suggestions will be appreciated.
 
use a bit of javascript on your page to update the img src from time to time. name the source image.php and append the current time to a query string

Code:
image.php?curTime=somerandomdata

the changing time as a query variable is for cachebusting

then on the php side rename the script image.php and change it slightly as follows:

Code:
<?php
$imageDirectory = "/upload/";
$dirHandle = opendir($_SERVER['DOCUMENT_ROOT'].$imageDirectory);
while (false !== ($dirFile = readdir($dirHandle))){
    if ($dirFile != "." && $dirFile != ".." && !is_dir($dirFile) ){
        $randomFile[] = $dirFile;
    }
}
closedir($dirHandle);
header ('Content-type: image/jpeg');
readfile ( $imageDirectory.$randomFile[rand(0,count($randomFile)-1)] );
exit;
?>

for performance reasons you might wish to create the randomisation at the first visit and store the random order in a session variable.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top