Jump to content

opendir issue


Pioden

Recommended Posts

Hi folks,

 

I'm listing files in a directory using the opendir function. Here's the code:

 

// List files in image directory
if ($handle1 = opendir($img_path)) {
   while (false !== ($file = readdir($handle1)))
      {
          if ($file != "." && $file != "..")
  {
          	$imglist .= "$file";
          }
       }
  closedir($handle1);
  }

 

Everything is fine EXCEPT that the script also lists subdirectories. Is there a way of hiding/not displaying subdirectories? The PHP manual doesn't seem to offer much on this subject :-(

 

TIA

 

Huw

Link to comment
https://forums.phpfreaks.com/topic/120318-opendir-issue/
Share on other sites

Oh i see you want just to show files.

easily done with a simple if statement like so:

 

<?php

// List files in image directory
if ($handle1 = opendir($img_path)) {
   while (false !== ($file = readdir($handle1))) {
          if ($file != "." && $file != ".." && is_file($img_path."/".$file)) {
          	$imglist .= $file;
          }
    }
    closedir($handle1);
}
?>

 

where you assign the file to a list: $imglist .= $file;

you should really be adding them to an array: $imglist[] = $file;

 

This way you can iterate over each file and manipulate them as necessary (add padding, seperate into boxes/links or whatever).

you can also search for specific extensions like .gif / .jpg / .png etc like so:

 

<?php

// List files in image directory
if ($handle1 = opendir($img_path)) {
while (false !== ($file = readdir($handle1))) {
	if ($file != "." && $file != ".." && is_file($img_path."/".$file)) {
		$ext = substr($file,-3);
		if($ext == "jpg" || $ext == "gif" || $ext == "bmp" || $ext == "png"){
			$imglist .= $file; // $imglist[] = $file;
		}
	}
}
closedir($handle1);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/120318-opendir-issue/#findComment-619892
Share on other sites

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.