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

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

报告相同问题?

悬赏问题

  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题