Monday 16 July 2018

PHP’s ftp_nlist() Returning False, Even When Files Definitely Exist

PHP’s ftp_nlist() Returning False, Even When Files Definitely Exist

PHP comes with a whole host of FTP functions built-in that makes performing FTP operations quick and easy. One of the things you can do is to use the ftp_nlist() function to get the contents of an entire directory.
This is exactly what I was doing today and went something along the lines of this:

  1. $ftp_connect = ftp_connect("123.123.123.123");  
  2.   
  3. $ftp_login = ftp_login($ftp_connect"ftp_username""ftp_password");  
  4.   
  5. if ( ! $ftp_contents = ftp_nlist($ftp_connect".") )  
  6. {  
  7.     echo 'Failed to get files from the current directory';  
  8. }  
  9. else  
  10. {  
  11.     // Do things with files here  
  12. }  
  13.   
  14. ftp_close($ftp_login);  
Above we’re connecting to the FTP server, then logging in before getting the contents of the current directory. For some reason my script was falling into the case where the return from ftp_nlist() was false, meaning I couldn’t then get the contents of the folder.
Note: The second parameter of our call to ftp_nlist is the directory that we want to get the contents for. By passing “.” we mean the current directory.
There were no errors output, no notices, no warnings… nothing.
The Solution
After a little digging around it turned out, due to being behind a firewall, I needed to activate passive mode by using the ftp_pasv() function. And I quote:
In passive mode, data connections are initiated by the client, rather than by the server. It may be needed if the client is behind firewall.
So after adding the following:

  1. ftp_pasv($ftp_connect, true);  
after our call to ftp_login() I instantly started getting files back as expected.

0 comments:

Post a Comment