tags:

views:

54

answers:

4

I want to list all files on an FTP server using PHP. According to RFC 959 the FTP command LIST is allowed to print arbitrary human-readable information on files/folders, which seems to make it impossible to determine the file type correctly. But how do other FTP clients manage to distinguish files and folders? Is there an unwritten standard or such?

+1  A: 

I think a lot depends on the ftp server. The ftp servers around in my college give an output to "ls" command in the following format:

drwxr-xr-x    2 5609     1510         1896 Oct 31  2007 practice
-rw-r--r--    1 5609     1510          646 Feb 08  2009 prgrm1.c

that clearly shows that practice is a directory, while prgrm1.c is a file.

+1  A: 

you can use ftp_rawlist(). the get the items that start with "d" (means directory) eg

$ftp_server="someserver";
$ftp_user_name="someuser";
$ftp_user_pass="somepassword";
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if ((!$conn_id) || (!$login_result)) {
    echo "FTP connection has failed!";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name";
    exit;
} else {
    echo "Connected to $ftp_server, for user $ftp_user_name";
    $buff = ftp_rawlist($conn_id, '/');
    $dirs = preg_grep("/^d/",$buff);
    print_r($dirs);

}
ghostdog74
Is that guaranteed? Is the server not free to print `t` as first character if it's a folder? Or has this 'standard' been established without any mentioning in the RFCs?
soulmerge
AFAIK this (the output of UNIX ls -l) is a "de facto" standard.
jpalecek
A: 

why not do a CD on the file/path? if an error occurs, it's a file.

stillstanding
... except when it's a directory you don't have permission to enter.
jpalecek
Then a detailed check of the response is in order
stillstanding
A: 

I finally found the extension to the FTP protocol which implements the desired behaviour: the command is called MLSD and can be found on page 23 of RFC 3659. I'll use that as default and try to parse the output of LIST as if it was returned by ls -l as a fallback.

soulmerge