Reputation: 63
I have a PHP script that works when using ftp_connect
, but when using ftp_ssl_connect
it doesn't work.
Does anyone know why?
When running the script on a remote server that only requires ftp_connect
, the script below works without issue. But as soon as I switch to a server requiring ftp_ssl_connect
the script hangs and I end up with a 504 error with no indication of what went wrong.
I have attempted debugging by removing all the script except for the login, and the login seems to work on its own, but when I add in any requests beyond login it causes a 504
<?php
// set up basic ssl connection
$ftp = ftp_ssl_connect('myremotesite.com');
// login with username and password
$login_result = ftp_login($ftp, 'username', 'password');
if (!$login_result) {
// PHP will already have raised an E_WARNING level message in this case
die("can't login");
}
// get list of files on given path
$files = ftp_nlist($ftp, '/1668161919_DATA/*add.zip') or
die("Could not find file");
$mostRecent = array(
'time' => 0,
'file' => null
);
foreach ($files as $file) {
// get the last modified time for the file
$time = ftp_mdtm($ftp, $file);
if ($time > $mostRecent['time']) {
// this file is the most recent so far
$mostRecent['time'] = $time;
$mostRecent['file'] = $file;
}
}
ftp_get($ftp,
"/home/mysite/public_html/wp-content/uploads/data-zipped/target.zip",
$mostRecent['file'], FTP_BINARY);
ftp_delete($ftp, $mostRecent['file']);
ftp_close($ftp);
?>
Upvotes: 2
Views: 833
Reputation: 202088
Your code is using the (default) active mode. In the active mode the client (PHP in this case) sends its local IP address (in PORT
command) to the server for the server to connect back for data transfers. If you are behind firewall/NAT (what I assume you are) that usually stops working, as the local IP address is not valid out of your network, so the server fails to connect back.
Why it works for you with plain unencrypted FTP (ftp_connect
) anyway is likely because your firewall/NAT translates the local IP address in the PORT
command to externally valid one. But it cannot do that with encrypted FTP (ftp_ssl_connect
).
In general, nowadays, using active mode (due to ubiquitous firewalls and NAT) is troublesome. Use the passive mode. Add the following call after the ftp_login
:
ftp_pasv($ftp, true) or die("Cannot switch to the passive mode");
See also PHP ftp_put fails.
Upvotes: 1