Search code examples
phpftptimeout

PHP ftp_connect timeout parameter Not working


$conn = ftp_connect($server['host'], $server['port'], 5);
ftp_get(@$conn, 'a.txt', 'a.txt', FTP_ASCII);

Above code is working 30 minutes for a large a.txt file and never ends despite 5 seconds timeout setting, which according to ftp_connect manual "specifies the timeout in seconds for all subsequent network operations."

Please advice


Solution

  • If you want to abort the download, when it takes too long, you cannot use ftp_get as it is blocking.


    You have two options. Either use ftp_nb_get:

    $ret = ftp_nb_get($conn_id, $local_path, $remote_path, FTP_BINARY);
    
    while ($ret == FTP_MOREDATA)
    {
        if (takes_too_long) break;
        $ret = ftp_nb_continue($conn_id);
    }
    

    Or FTP URL protocol wrapper:

    $url = "ftp://username:[email protected]/remote/source/path/file.zip";
    $hin = fopen($url, "rb") or die("Cannot open source file");
    $hout = fopen("/local/dest/path/file.zip", "wb") or die("Cannot open destination file");
    
    while (!feof($hin))
    {
        if (takes_too_long) break;
        $buf = fread($hin, 10240);
        fwrite($hout, $buf);
    }