©
This document uses PHP Chinese website manual Release
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
ftp_nb_get — 从 FTP 服务器上获取文件并写入本地文件(non-blocking)
$ftp_stream
, string $local_file
, string $remote_file
, int $mode
[, int $resumepos
] ) ftp_nb_get() 函数用来获取参数 remote_file
指定的的远程文件,并保存到由参数 local_file
指定的本地文件。传输模式参数
mode
只能为 FTP_ASCII
(文本模式) 或 FTP_BINARY
(二进制模式) 两种。与 ftp_get()
函数不同的是,此函数上传文件的时候采用的是异步传输模式,也就意味着在文件传送的过程中,你的程序可以继续干其它的事情。
返回 FTP_FAILED
, FTP_FINISHED
或 FTP_MOREDATA
。
Example #1 ftp_nb_get() 实例
<?php
// 开始下载
$ret = ftp_nb_get ( $my_connection , "test" , "README" , FTP_BINARY );
while ( $ret == FTP_MOREDATA ) {
// 这里可以插入其它代码
echo "." ;
// 继续下载...
$ret = ftp_nb_continue ( $my_connection );
}
if ( $ret != FTP_FINISHED ) {
echo "下载中出错..." ;
exit( 1 );
}
?>
Example #2 使用 ftp_nb_get() 函数断线续传
<?php
// 开始
$ret = ftp_nb_get ( $my_connection , "test" , "README" , FTP_BINARY ,
filesize ( "test" ));
// 或: $ret = ftp_nb_get ($my_connection, "test", "README",
// FTP_BINARY, FTP_AUTORESUME);
while ( $ret == FTP_MOREDATA ) {
// 可以插入其它代码
echo "." ;
// 继续传送...
$ret = ftp_nb_continue ( $my_connection );
}
if ( $ret != FTP_FINISHED ) {
echo "下载出错..." ;
exit( 1 );
}
?>
Example #3 用 ftp_nb_get() 在 100 的位置断线续传并存为 "newfile"
// 禁止自动搜寻
ftp_set_option ($my_connection, FTP_AUTOSEEK, FALSE);
// 开始
$ret = ftp_nb_get ($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {
...
// 继续下载...
$ret = ftp_nb_continue ($my_connection);
}
在上边的例子中,"newfile" 文件比服务器上的文件
"README" 要小 100 字节。这是因为我们是从文件的偏移量 100
处开始读取的,如果没有禁止 FTP_AUTOSEEK
,则
"newfile" 的前 100
字节将会是 '\0'。
参见 ftp_nb_fget() , ftp_nb_continue() , ftp_get() 和 ftp_fget() 。
[#1] passerbyxp at gmail dot com [2012-01-04 20:24:36]
Note that you may have to keep calling ftp_nb_continue in order to complete the download. For example, if you do this:
<?php
ftp_nb_get($conn,$localfile,$remotefile,FTP_BINARY)
//do some LONG time work
while(ftp_nb_continue($conn)!=FTP_FINISHED){}
?>
Your local file may only contains a few kilobytes and the later ftp_nb_continue will keep raising warning of no more data (due to connection time out, I guess).
So you may want to do this instead:
<?php
$dl=ftp_nb_get($conn,$localfile,$remotefile,FTP_BINARY)
//part of long time work
if(ftp_nb_continue($conn)==FTP_MOREDATA) {}
//part of long time work
if(ftp_nb_continue($conn)==FTP_MOREDATA) {}
//continue to do this until you finish the long time work
while(ftp_nb_continue($conn)==FTP_MOREDATA){}
?>
This happened on my Windows XP + PHP 5.3.8 under CLI. Hope this helps someone.