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

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

报告相同问题?

悬赏问题

  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题