Ronak Patel Ronak Patel - 7 months ago 21
PHP Question

Use opendir one time instead of using it in for loop

I have below code to get content from remote directory.

$dirHandle = opendir("ssh2.sftp://$sftp/".PATH_OUT);
while (false !== ($file = readdir($dirHandle))) {
// something...
}


Now, the thing is, above code is in
forloop
. when I put
$dirHandle = opendir("ssh2.sftp://$sftp/".PNB_PATH_OUT);
outside of forloop then it gives me required result only for first record. So, obviously it's
readdir
is not working for second record in
forloop
.

How can I do this in such a way that I need to use
opendir
only once and use that connection more than 1 time?

Required Solution

$dirHandle = opendir("ssh2.sftp://$sftp/".PATH_OUT);
for(...){
while (false !== ($file = readdir($dirHandle))) {
// something...
}
}

Answer

Your while loop is traversing the entire directory until there are no more files, in which case readdir returns false. Therefore any time readdir is called after the first traversal, it will just return false because it is already at the end of the directory.

You could use rewinddir() in the for loop to reset the pointer of the directory handle to the beginning.

$dirHandle = opendir("ssh2.sftp://$sftp/".PATH_OUT);
for(...){
    rewinddir($dirHandle);
    while (false !== ($file = readdir($dirHandle))) {
      // something...
    }
}

Since the sftp stream appears to not support seeking, you should just store the results you need and do the for loop after the while loop. You are, after all, traversing the same directory multiple times.

$dirHandle = opendir("ssh2.sftp://$sftp/".PATH_OUT);
while (false !== ($file = readdir($dirHandle))) {
  $files[] = $file;
}
for(...){
    // use $files array
}