Php 复制vs Curl以在我的服务器上保存外部文件

Php 复制vs Curl以在我的服务器上保存外部文件,php,file,curl,Php,File,Curl,哪种方式将外部文件保存到我的服务器最快。为什么和如何 使用Curl: $ch = curl_init(); $fp = fopen ($local_file, 'w+'); $ch = curl_init($remote_file); curl_setopt($ch, CURLOPT_TIMEOUT, 50); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt

哪种方式将外部文件保存到我的服务器最快。为什么和如何

使用Curl:

$ch = curl_init();
$fp = fopen ($local_file, 'w+');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_exec($ch);
curl_close($ch);
fclose($fp);
使用副本:

copy($extFile, "report.csv");

这主要取决于协议(例如,如果是本地文件,则copy()会更快),但由于您说的是“远程文件”,curl可能会更快。您使用的是
CURLOPT_编码
CURLOPT_FOLLOWLOCATION
,我想这意味着它是通过http传输的,其中curl通常比copy快得多,至少有两个原因:

1:PHP的fopen http包装器不使用压缩,但是当您将
CURLOPT_ENCODING
设置为此处清空字符串时,您会告诉curl尽可能使用压缩。(这取决于libcurl的编译方式,
gzip
deflate
压缩通常与libcurl一起编译。)

2:copy()一直从套接字读取,直到远程服务器关闭连接,这可能比文件完全下载要晚得多。同时,curl将只读取等于
内容长度:
-http头的字节,然后关闭连接本身,这通常比在远程服务器关闭连接之前暂停read()要快得多(copy()关闭连接,curl_exec()不关闭连接)

但唯一确定ofc的方法是TIAS

$starttime=microtime(true);
$ch = curl_init();
$fp = fopen ($local_file, 'w+');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_exec($ch);
curl_close($ch);
fclose($fp);
echo "used ".(microtime(true)-$starttime)." seconds.\n";
vs

  • 提供大约微秒的精度(IEEE 754双浮点精度可能会对其造成一定程度的破坏,但可能不够重要。)
$starttime=microtime(true);
copy($extFile, "report.csv");
echo "used ".(microtime(true)-$starttime)." seconds.\n";