PHP Display a percentage of progress of ftp_get?

前端 未结 3 557
青春惊慌失措
青春惊慌失措 2020-12-20 02:41

I have a working FTP file download script.
The files I am downloading will be about 2-4 GB per day.
I was wondering if there was a way to get the percent of the file

相关标签:
3条回答
  • 2020-12-20 03:31

    You should try buffer flush - ob_flush() and flush().

    This technique works, I already used it. here is a tutorial

    I am sure that you can wind yourself some more. Just google "progress php flush buffer"

    0 讨论(0)
  • 2020-12-20 03:33

    It can be implemented easily using FTP URL protocol wrappers:

    $url = "ftp://username:password@ftp.example.com/remote/source/path/file.zip";
    
    $size = filesize($url) or die("Cannot retrieve size file");
    
    $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))
    {
        $buf = fread($hin, 10240);
        fwrite($hout, $buf);
        echo "\r".intval(ftell($hout)/$size*100)."%";
    }
    
    echo "\n";
    
    fclose($hout);
    fclose($hin);
    

    Regarding your attempts using ftp_nb_get:
    The filesize caches the results, so calling it repeatedly will get you the same value. You have to call clearstatcache.

    A full code is like:

    $conn_id = ftp_connect("ftp.example.com");
    ftp_login($conn_id, "username", "password");
    
    ftp_pasv($conn_id, true);
    
    $local_path = "/local/dest/path/file.zip";
    $remote_path = "/remote/source/path/file.zip";
    $size = ftp_size($conn_id, $remote_path);
    
    $ret = ftp_nb_get($conn_id, $local_path, $remote_path, FTP_BINARY);
    
    while ($ret == FTP_MOREDATA)
    {
      clearstatcache(false, $local_path);
      echo "\r".intval(filesize($local_path)/$size*100)."%";
      $ret = ftp_nb_continue($conn_id);
    }
    
    echo "\n";
    

    Alternatively use ftp_nb_fget and query the file handle, like my first example.

    0 讨论(0)
  • 2020-12-20 03:41

    Try using the non-blocking version ftp_nb_get() and ftp_nb_continue() in a loop, and check for the saved file's size.

    0 讨论(0)
提交回复
热议问题