PHP FTP函数

PHP ftp_nb_fget() 函数从 FTP 服务器下载文件,并将其保存到打开的本地文件。

该函数与ftp_fget()的区别在于该函数异步检索文件,这样您的程序就可以在下载文件时执行其他操作。

语法

ftp_nb_fget(ftp, open_file, server_file, 
             mode, offset) 
  • 1

参数

ftp必填。 指定要使用的 FTP 连接。
open_file必需。 指定存储数据的打开文件指针。
server_file必需。 指定要下载的服务器文件。
mode可选。 指定传输模式。必须是 FTP_ASCII 或 FTP_BINARY。
offset可选。 指定远程文件中开始下载的位置。

返回值

返回以下任意值:

  • FTP_FAILED:异步传输失败。
  • FTP_FINISHED:异步传输已完成。
  • FTP_MOREDATA:异步传输仍处于活动状态。

示例:

下面的示例显示了ftp_nb_fget( ) 函数。

<?php
//要使用的FTP服务器
$ftp_server = "ftp.example.com";

//FTP 连接的用户名
$ftp_user = "user";
  
//用户密码
$ftp_pass = "password";
   
//建立连接或者连接失败
$ftp = ftp_connect($ftp_server)
    or die("Could not connect to $ftp_server");
   
if($ftp) {
  echo "Successfully connected to $ftp_server!\n";
 
  //尝试登录
  if(@ftp_login($ftp, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";

    //本地打开文件指针在其中
    //我们存储数据
    $open_file = fopen("local_demo.txt", "w");
      
    //服务器文件路径
    //需要下载
    $server_file = "server_demo.txt";
      
    //下载指定服务器文件
    //并保存以打开本地文件
    $ret = ftp_nb_fget($ftp, $open_file, 
                    $server_file, FTP_ASCII);

    while ($ret == FTP_MOREDATA) {
      //继续下载...
      $ret = ftp_nb_continue($ftp);
    }

    if ($ret == FTP_FINISHED) {
      echo "Successfully written to $open_file\n";
    } else {
      echo "Error while downloading $server_file\n";
      exit(1);
    }

    //关闭文件指针
    fclose($open_file);
    
  } else {
    echo "Couldn't connect as $ftp_user\n";
  }
 
  //关闭连接
  if(ftp_close($ftp)) {
    echo "Connection closed successfully!\n"; 
  } 
}
?> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

上述代码的输出将是:

Successfully connected to ftp.example.com!
Connected as user@ftp.example.com
Successfully written to local_demo.txt
Connection closed successfully! 
  • 1
  • 2
  • 3