©
本文档使用
php.cn手册 发布
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
ftp_nb_fget — 从 FTP 服务器获取文件并写入到一个打开的文件(非阻塞)
$ftp_stream
, resource $handle
, string $remote_file
, int $mode
[, int $resumepos
= 0
] )ftp_nb_fget() 从远程 FTP 服务器获取一个文件
本函数和 ftp_fget() 函数的区别是 本函数是异步方式获取文件的, 所以在下载文件的过程中你的程序还可以执行其他操作。
ftp_stream
FTP 连接标示符。
handle
用来存储数据的一个已经打开的文件句柄。
remote_file
远程文件路径。
mode
传输模式,必须是 FTP_ASCII
或者
FTP_BINARY
。
resumepos
远程文件开始下载的位置(即从远程文件的哪个字节开始下载)。
返回 FTP_FAILED
或 FTP_FINISHED
或 FTP_MOREDATA
。
Example #1 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 );
?>
[#1] pilif at pilif dot ch [2004-11-16 05:53:34]
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