php - 流式传输文件时 CURL 比 fread 慢?如何加速 CURL

标签 php curl stream fread

我正在尝试制作一个脚本来下载文件的一部分。 只需使用 CURL 和 fread 进行测试,我意识到流式传输过程中的 CURL 比 fread 慢。 为什么?如何加快文件流的 curl ? 我不喜欢使用 fread , fopen 因为我在流媒体过程中需要有限的时间。

这是我的示例代码。

$start = microtime(true);
$f = fopen('http://news.softpedia.com/images/news2/Debian-Turns-15-2.jpeg','r');
$response = fread($f, 3); echo $response.'<br>';
$response = fread($f, 3); echo $response.'<br>';
$response = fread($f, 3); echo $response.'<br>';
$response = fread($f, 3); echo $response.'<br>';
$response = fread($f, 3); echo $response.'<br>';

$stop = round(microtime(true) - $start, 5);
echo "{$stop}s";
exit();

fread/fopen 只需1.1s

$start = microtime(true);
$curl = curl_init('http://news.softpedia.com/images/news2/Debian-Turns-15-2.jpeg');
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_RANGE, "0-2");
$response = curl_exec($curl);echo $response.'<br>';

curl_setopt($curl, CURLOPT_RANGE, "3-5");
$response = curl_exec($curl);echo $response.'<br>';

curl_setopt($curl, CURLOPT_RANGE, "6-8");
$response = curl_exec($curl);echo $response.'<br>';

curl_setopt($curl, CURLOPT_RANGE, "9-11");
$response = curl_exec($curl);echo $response.'<br>';

curl_setopt($curl, CURLOPT_RANGE, "12-14");
$response = curl_exec($curl);echo $response.'<br>';
curl_close($curl);

$stop = round(microtime(true) - $start, 5);
echo "{$stop}s";
exit();

curl 耗时约 2.5 秒。 如果我采取更多步骤来下载文件的更多部分。 curl 会更慢。

为什么 curl 比较慢?什么解决方案?

最佳答案

它总是比较慢,因为您添加了额外的 HTTP 调用往返。每个 curl_exec 都是一个 HTTP 请求。

关于php - 流式传输文件时 CURL 比 fread 慢?如何加速 CURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19418877/

相关文章:

PHP:检查时间戳后是否已经过了一周

php - 通过 curl 发送图像

c++ - curl_easy_perform 返回 CURLE_WRITE_ERROR,但我不会写任何东西

c++ - 如何在 C++ 中对二进制数据使用 >> 和 << 运算符?

java - 如何保持 "Hello World"类型服务器运行

php - 使用 ajax 创建的字段保存表中的更改

php - 为什么password_verify返回false?

php - 连接注入(inject)故障排除

curl - 使用命令行 cURL 发布文件内容

c++ - 在char数组(流)c++中查找和替换字符串的函数