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

July 17th, 2013 - Posted by Steve Marks to PHP, Web Development.

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:

$ftp_connect = ftp_connect("");

$ftp_login = ftp_login($ftp_connect, "ftp_username", "ftp_password");

if ( ! $ftp_contents = ftp_nlist($ftp_connect, ".") )
    echo 'Failed to get files from the current directory';
    // Do things with files here


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:

ftp_pasv($ftp_connect, true);

after our call to ftp_login() I instantly started getting files back as expected.

Tags: , ,
This entry was posted on Wednesday, July 17th, 2013 at 7:32 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (2)
  1. This helped me alot. Thanks for sharing this piece of information :)

  2. Cristemir says:

    Muito obrigado, seu post foi muito Ăștil.