SIZE command is not required. You can simply use the ftp_nlist() function to do this because the FTP LIST command allows you to transfer the directory as well as the file as an argument.
Although the PHP documentation does not mention that it is specified in RFC 959 (page 32) and it works. Here is an example. (Thanks Debian! )
$server = 'ftp.us.debian.org'; $port = 21; $user = 'anonymous'; $pwd = 'foo@bar.xxx'; $conn = ftp_connect($server); $ret = ftp_login($conn, $user, $pwd); foreach(array( 'debian/README.html', 'NOT_FOUND.html' ) as $file) { $listing = ftp_nlist($conn, $file); if(empty($listing)) { echo "$file was not found on $server\n"; } else { echo "$file was found on $server\n"; } }
Or, expressed as a function:
function ftp_file_exists( $server, $filename, $user = 'anonymous' , $pwd = '', $port = 21 ) { $conn = @ftp_connect($server); if($conn === FALSE) { die("Failed to connect to $server"); } $ret = @ftp_login($conn, $user, $pwd); if($ret === FALSE) { die("Failed to login at $server"); } $listing = @ftp_nlist($conn, $file); if($listing === FALSE) { die("Failed to obtain LIST response from $server"); } return !empty($listing); }
In the comments there was a discussion of how useful and reliable LIST results can be. Let me say a few additional sentences to this ...
Creating files on the server
Please note that you should avoid relying on something like:
if(file_not_exists_on_server($filename)) { create_file_on_server($filename); }
because it is possible that the file will be created by another client between the first and second functions. Although this is true for local file systems, it can happen in distributed client server applications more easily, due to the longer response time compared to the local file system, and because of the possibly many even anonymous clients (for example, in the example above)
When creating files remotely, I suggest that you follow a strong naming scheme in public folders for writing to avoid collisions. Following this pattern, just write and don't care. The worst thing that can happen is that you are rewriting something that someone else accidentally created. But who creates something like /client/id/file_name.txt accident?
Download files from the server or move, delete files on the server
When you try to perform one of these operations, it does not matter if the files exist or not before the operation. Just do it. But if this fails, you need to handle the errors correctly.