Ashley Sheridan​.co.uk

Listing Directories In An FTP Location

Posted on

A question that I saw recently on a mailing list was how to determine whether a file (I'll use the Unix terminology here: everything is a file) on an FTP connection is a directory or a file. One suggestion was to use the FTP file wrapper in PHP and then use the is_file() and is_dir() functions to determine the type. I noted at the time that this wasn't a perfect solution, as it relied on the FTP file wrapper to be available, and some hosting suppliers don't give this as an option, and suggested that ftp_rawlist() could be used instead, as a more viable option.

I didn't go into too much detail at the time, so here is a working example:

<?php $ftpcon = ftp_connect("domain"); $login_result = ftp_login($ftpcon, "username", "password"); $list = ftp_rawlist($ftpcon, '/www'); ftp_close($ftpcon); for($i=0; $i<count($list); $i++) { $parts = explode(' ', $list[$i]); $type = substr($parts[0], 0, 1); if($type == 'd') { print $parts[count($parts)-1] . ''; } } ?>

The first few lines connect to, list and then close an FTP connection, storing the directory listing in $list. Each entry in this list is an entry in the directory listing, whether that be a file, directory, symlink, etc, in verbose format.

The parts of each entry that are important are the first and last when the string is separated at each space character, as these contain the type & permissions and the filename respectively.

The type & permissions part is in the form 'drwxrwxrwx', with each part indicating an attribute or permission. For example, if the first character is a 'd', the entry is a directory. The next 9 characters indicate what level of permission (read, write and execute) the owner, group and others has for this file.

The effect of the script is to output a list of directories that exist inside of the directory that was opened in line 5.