douyi9787 2015-01-19 16:19
浏览 281
已采纳

PHP Curl直接下载/流式部分内容

I want to send/stream Files from an other Website/Webadress directly to the user, without storing the Files on my Server. The Files are Archives about 100MB to 1GB

The download with one thread works fine. Here is my Code:

$ch5 = curl_init();
if (isset($_SERVER['HTTP_RANGE'])) {
    //http://stackoverflow.com/questions/157318/resumable-downloads-when-using-php-to-send-the-file
    preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
    $offset = intval($matches[1]);
    $end = $matches[2] || $matches[2] === '0' ? intval($matches[2]) : $size - 1;
    curl_setopt($ch5, CURLOPT_RANGE, "$offset-$end");
}
curl_setopt($ch5, CURLOPT_URL, $direct_link);
curl_setopt($ch5, CURLOPT_TIMEOUT, 3550); 
curl_setopt($ch5, CURLOPT_CONNECTTIMEOUT, 15); 
curl_setopt($ch5, CURLOPT_HEADERFUNCTION, 'readHeader');
curl_exec($ch5);
$dlsize = curl_getinfo($ch5,CURLINFO_SIZE_DOWNLOAD );
$time = curl_getinfo($ch5,CURLINFO_TOTAL_TIME);
curl_close($ch5);

function readHeader($ch, $header) // Send header from the Downloaded file to the User
{
    header($header);
    return strlen($header);
}

The problem is that PHP Download the complete file if the request contains an Range like "Range: bytes=0-" and sending it to the user. But the User download much slower(Cause slower download speed) then downloading it to my Server, but if the file is completely downloaded, the file isn't available on the external Server. And when the Client make an Range Request for the second half or something else the Request goes to the external Server and the file isn't available, cause it is already completely downloaded by the first request, but I cant access the Data or is there a way to get these Data, without saving them on my disk?

I want to save Bandwidth an want to give users the possibility to make Range Requests. So PHP should only download the amount the user really want to download or make a direct connection between the external Server and User.

Actually I am using nginx/1.6.2 and PHP 5.5.20-1 on Ubuntu 12.04.5

  • 写回答

1条回答 默认 最新

  • drf21989 2016-10-19 10:49
    关注

    I solved my problem by using nginx with X-Sendfile/X-Accel-Redirect . More Information here: wiki.nginx.org/XSendfile

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。