Jump to content

[SOLVED] Reading Files from a directory.


keeps21

Recommended Posts

I have some code which opens a directory, reads the files and assigns the file url to a variable - $image_url

 

        $baseUrl = "http://localhost";
        $gid = 1;
$dirname = "C:\\wamp\\www\\rd\\images\\galleries\\{$gid}";

$dir = opendir($dirname);

while (  false != ($file = readdir($dir)))  {
	if ( ($file != ".") and ($file != "..")  and ($file != "Thumbs.db") ) {
		$image_url = "{$baseUrl}/images/galleries/{$gid}/{$file}";
	}
}

closedir($dir);

 

This code provides me with the url of each file in the directory. I only really need to get the first file (i only need 1 file) in the directory but I'm not quite sure how to go about doing it.

 

At the minute to get just the one file I'm just overwriting $image_url; each time the loop iterates - though this isn't very efficient.

 

Any suggestions would be greatly appreciated.

Link to comment
https://forums.phpfreaks.com/topic/145900-solved-reading-files-from-a-directory/
Share on other sites

Nope it doesn't matter which image, just any image from that directory.

 

The problem is if I remove the while loop, the first "file" in the list is . or .. rather than the first image.

 

I guess I could sort this problem by checking that the file is an image, but again that would require a loop?

Cheers for your help.

 

Fixed code is as follows:

$baseUrl = "http://localhost";
$gid = 1;
$dirname = "C:\\wamp\\www\\rd\\images\\galleries\\{$gid}";
$dir = opendir($dirname);

while (  false != ($file = readdir($dir)))  {
    if ( ($file != ".") and ($file != "..")  and ($file != "Thumbs.db") ) {
        $image_url = "{$baseUrl}/images/galleries/{$gid}/{$file}";
        break; // break from while loop
    }
}
closedir($dir);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.