1

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...
    }
}
RNK
  • 5,582
  • 11
  • 65
  • 133

1 Answers1

0

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
}
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • It's giving me warming. Message: readdir() expects parameter 1 to be resource, null given – RNK Apr 22 '16 at 16:05
  • Debug $dirHandle, either opendir is failing or it's being set to null along the way. Update your post with your actual code so we can see. – Devon Bessemer Apr 22 '16 at 16:06
  • I was using `$dirHandle = rewinddir($dirHandle);`. Now, I used just `rewinddir($dirHandle);` and message is: `rewinddir(): stream does not support seeking` – RNK Apr 22 '16 at 16:07
  • according to your code: `rewinddir(): stream does not support seeking` – RNK Apr 22 '16 at 16:09
  • Most likely limited by sftp, I added an alternate solution, you really don't need to traverse the same directory multiple times, you could just store the information and use it later. – Devon Bessemer Apr 22 '16 at 16:12
  • Thanks. It's working in that way! I used `foreach-loop` – RNK Apr 22 '16 at 16:30