ftp_nb_get
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
ftp_nb_get — 从 FTP 服务器上获取文件并写入本地文件(non-blocking)
说明
ftp_nb_get(
resource
string
string
int
int
): int
resource
$ftp_stream
,string
$local_file
,string
$remote_file
,int
$mode
= FTP_BINARY
,int
$resumepos
= 0): int
ftp_nb_get() 在 FTP 服务器上获取指定的远程文件,并保存到本地。
和 ftp_get() 不同之处,在于此函数是通过异步的方式来获取文件,这意味着,你的程序可以在下载文件的同时,同步进行其它操作。
参数
-
ftp_stream
-
FTP 连接句柄。
-
local_file
-
保存到的本地文件路径(如果文件已存在会被覆盖)。
-
remote_file
-
远程文件路径。
-
mode
-
指定传输模式。必须是
FTP_ASCII
或FTP_BINARY
。 -
resumepos
-
开始下载文件的起始位置。
返回值
返回 FTP_FAILED
或 FTP_FINISHED
或 FTP_MOREDATA
。
更新日志
版本 | 说明 |
---|---|
7.3.0 |
mode 参数变为可选,之前是强制性的。
|
范例
示例 #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);
}
?>
示例 #2 通过 ftp_nb_get() 恢复下载一个文件
<?php
// 初始化
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY,
filesize("test"));
// OR: $ret = ftp_nb_get($my_connection, "test", "README",
// FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {
// 做你爱做的事
echo ".";
// 继续下载Ing...
$ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
echo "下载文件出错...";
exit(1);
}
?>
示例 #3 使用 ftp_nb_get() 从指定位置恢复下载文件
<?php
// 禁止 Autoseek
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 会比 FTP 服务器上的
README 文件小 100 bytes,因为开始下载的时候设置了偏移量为 100。如果我们不禁止
FTP_AUTOSEEK
,则 newfile 文件前面的 100 bytes 会变成
'\0'
。
参见
- ftp_nb_fget() - 从 FTP 服务器获取文件并写入到一个打开的文件(非阻塞)
- ftp_nb_continue() - 连续获取/发送文件(以不分块的方式 non-blocking)
- ftp_fget() - 从 FTP 服务器上下载一个文件并保存到本地一个已经打开的文件中
- ftp_get() - 从 FTP 服务器上下载一个文件

User Contributed Notes 1 note
passerbyxp at gmail dot com ¶
10 years ago
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.