• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • ftp_nb_fget()

    (PHP 4 >= 4.3.0, PHP 5, PHP 7)

    从 FTP 服务器获取文件并写入到一个打开的文件(非阻塞)

    说明

    ftp_nb_fget(resource $ftp_stream,resource $handle,string $remote_file[,int $mode= FTP_IMAGE[,int $resumepos= 0]]): int

    ftp_nb_fget()从远程 FTP 服务器获取一个文件

    本函数和ftp_fget()函数的区别是本函数是异步方式获取文件的,所以在下载文件的过程中你的程序还可以执行其他操作。

    参数

    $ftp_stream

    FTP 连接标示符。

    $handle

    用来存储数据的一个已经打开的文件句柄。

    $remote_file

    远程文件路径。

    $mode

    传输模式,必须是FTP_ASCII或者FTP_BINARY

    $resumepos

    远程文件开始下载的位置(即从远程文件的哪个字节开始下载)。

    返回值

    返回FTP_FAILEDFTP_FINISHEDFTP_MOREDATA

    更新日志

    版本说明
    7.3.0参数$mode变为可选参数。在之前的版本中,这是一个必填参数。

    范例

    ftp_nb_fget()函数例程

    <?php
    // 打开要写入的文件
    $file = 'index.php';
    $fp = fopen($file, 'w');
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
    // 初始化下载
    $ret = ftp_nb_fget($conn_id, $fp, $file, FTP_BINARY);
    while ($ret == FTP_MOREDATA) {
       // 其他要做的工作
       echo ".";
       // 继续下载...
       $ret = ftp_nb_continue($conn_id);
    }
    if ($ret != FTP_FINISHED) {
       echo "There was an error downloading the file...";
       exit(1);
    }
    // 关闭文件句柄
    fclose($fp);
    ?>
    

    参见

    • ftp_nb_get()从 FTP 服务器上获取文件并写入本地文件(non-blocking)
    • ftp_nb_continue()连续获取/发送文件(non-blocking)
    • ftp_fget()从 FTP 服务器上下载一个文件并保存到本地一个已经打开的文件中
    • ftp_get()从 FTP 服务器上下载一个文件
    If you want to monitor the progress of the download, you may use the filesize() Function.
    But note: The results of said function are cached, so you'll always get 0 bytes. Call clearstatcache() before calling filesize() to determine the actual size of the downloaded file.
    This may have performance implications, but if you want to provide the information, there's no way around it.
    Above sample extended:
    <?php
    // get the size of the remote file
    $fs = ftp_size($my_connection, "test");
    // Initate the download
    $ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
    while ($ret == FTP_MOREDATA) {
      
      clearstatcache(); // <- this is important
      $dld = filesize($locfile);
      if ( $dld > 0 ){
        // calculate percentage
        $i = ($dld/$fs)*100;
        printf("\r\t%d%% downloaded", $i);
      }  
      // Continue downloading...
      $ret = ftp_nb_continue ($my_connection);
    }
    if ($ret != FTP_FINISHED) {
      echo "There was an error downloading the file...";
      exit(1);
    }
    ?>
    Philip

    上篇:ftp_nb_continue()

    下篇:ftp_nb_fput()