Jump to content

readdir question


Cristian

Recommended Posts

Sorry for the noobie question, I am just a beginner still. I am trying to use the readdir function to echo back all the contents of a folder. The directory that I want to read back has 31 empty folders. I am able to get them to read back, but they are in a random order and there are two additional files at the top named "." and ".." -- any idea how to fix these? Here is my code and pictures:

 

$path = "c:/test/";

if(is_dir($path)) {

if($dir_handle = opendir($path)) {

while($filename = readdir($dir_handle)) {

echo "filename: {$filename}<br>";

}

closedir($dir_handle);

}

}

 

post-129076-13482403230879_thumb.jpg

post-129076-1348240323103_thumb.jpg

Link to comment
Share on other sites

The '.' and '..' are special links within the file system that allow you to traverse up the directory structure. You can simply add some if() conditions in your logic to skip them (see example #2 in the manual). Or, alternatively, you can use glob() - which is my preference when reading files/folders. It simply returns an array and never includes those two special links.

 

As for the order - it is not random. It is in alphanumeric order. Windows has logic to do a "natual" sort how a human would order text with trailing numbers. PHP has a couple functions to do this type of sorting on an array. So, either use readdir() to dump the contents into  an array first or used glob(). Then use either natsort() [case sensitive] or natcasesort() [case insensitive] to sort the array before outputting it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.