Reputation: 2783
One of my CLI scripts downloads files via FTP.
The script opens an FTP connection, logs in, downloads the necessary files, and sleeps. Every so often it checks for the files again. This script is expected to run for days on end, as a daemon.
I want to be able to re-use an open connection (so I don't have to re-connect every loop).
$ftpconn = false;
$ftplogin = false;
while(1){
sleep(25);
if(!$ftpconn){
$ftpconn = ftp_connect(HOST);
}
if(!$ftplogin){
$ftplogin = ftp_login($ftpconn, USER, PASS);
}
// Do FTP stuff here
}
My question is this. Do both ftp_connect
and ftp_login
timeout? And if so, will $ftpconn
and $ftplogin
change to FALSE when that happens?
Thanks.
Upvotes: 3
Views: 2558
Reputation: 3606
I was having the same problem. I also have a compounding problem: for some reason, there's no way to distinguish between an actual error and an empty response (when the file list is empty). ftp_nlist
returns FALSE in both cases (also noted here), and ftp_rawlist
returns an empty array in both cases.
So my first hunch was to do a cheap call, like ftp_pwd
, to see if the connection is still open. However, PHP does some caching apparently, so that won't work. However, you can force PHP to run the same call over the FTP connection with this:
$result = ftp_raw($ftpConnection, 'pwd');
print_r($result);
// Array
// (
// [0] => 257 "/www/html"
// )
This should always give a response (given a working FTP connection), which will be an array with a single item. If there's an error, it will be an empty array.
Upvotes: 0
Reputation: 1671
You're best bet on this is to implement your connection process. Then build your logic for trying to check for the file. (I'm assuming using something like ftp_nlist). ftp_nlist will return a FALSE if there is an error for any reason. At which point you can have your code close the existing connection using ftp_close (Which will give a FALSE if the connection was already closed for whatever reason) and then run the connection sequence again.
You'll want to build in logic that if the ftp_nlist fails more than a few times to exit out of your application. Unfortunately the various ftp_* commands don't have a lot of depth in regards to identifying why a function failed so you will have to build extra logic around it to compensate.
Upvotes: 1