ftp_rawlist returns false when connected [duplicate]

$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");

if (@ftp_login($ftp_conn, $ftp_username, $ftp_userpass))
{
    $path = "./";
    $path1="./test";
    $file = "test.txt";
    $file_list = ftp_nlist($ftp_conn,$path);
}
// close connection
ftp_close($ftp_conn);

The above is the code which I am using. It is working fine for me on my Windows local machine, Windows server machine, Linux local machine, but somehow it fails on the Linux server machine. ftp_nlist returns false. Can someone tell me what might be the reason?

Any help appreciated. Thank you.


Solution 1:

Most typical cause of problems with ftp_nlist (or any other transfer command like ftp_get, ftp_put, ftp_rawlist) is that PHP defaults to the FTP active mode. And in 99% cases, one has to switch to the FTP passive mode, to make the transfer working. Use the ftp_pasv function.

$connect = ftp_connect($ftp) or die("Unable to connect to host");
ftp_login($connect, $username, $pwd) or die("Authorization failed");
// turn passive mode on
ftp_pasv($connect, true) or die("Passive mode failed");

See also my article on the active and passive FTP connection modes.


Further, if your FTP server is reporting an incorrect IP address in the response to the PASV command, you might need to workaround it by using:

ftp_set_option($connect, FTP_USEPASVADDRESS, false);

See PHP FTP + Passive FTP Server Behind NAT.

Though the right solution in this case, is to get the server fixed.


If none of this help, make sure you have tested, if you can even retrieve the directory listing using any commandline/GUI FTP client running on the same machine as your PHP code. You might not have a programming question in the first place.