Jump to content

Recommended Posts

I am trying to oder folders before files when i display a directory through php.

 

Though they do not seem to work with the following code .... anyone see what's wrong?

 

if (is_dir($dir)){
if ($dh = opendir($dir)) {

              // removes two hidden files "." and ".."
              if($file != "." && $file != "..") {

	  while ((($file = readdir($dh)) !== false) && (filetype($dir . $file) == "dir" )) {

			echo $file;
                                echo 'folder';
	  }

	  while ((($file = readdir($dh)) !== false) && (filetype($dir . $file) == "file" )) {

           			echo $file;
                                echo 'file';


		}

	}
}
closedir($dh);
}

 

cheers

 

d

Link to comment
https://forums.phpfreaks.com/topic/51666-while-loops-and-readdir-function-problem/
Share on other sites

Both your loops have the same 1st condition, so once the first loop finishes the second loop will obviously never execute.

 

while ((($file = readdir($dh)) !== false)...
...	
while ((($file = readdir($dh)) !== false)...

 

You need to reopen the directory between your loops like so:

 

if (is_dir($dir)){
if ($dh = opendir($dir)) {

              // removes two hidden files "." and ".."
              if($file != "." && $file != "..") {

	  while ((($file = readdir($dh)) !== false) && (filetype($dir . $file) == "dir" )) {

			echo $file;
                                echo 'folder';
	  }

          closedir($dh);
                  $dh = opendir($dir); // Reopen the directory

	  while ((($file = readdir($dh)) !== false) && (filetype($dir . $file) == "file" )) {

           			echo $file;
                                echo 'file';


		}

	}
}
closedir($dh);
}

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.