简体   繁体   English

使用外部链接PHP的readfile()进行可恢复的下载

[英]Make resumable downloads with readfile() of external link PHP

I have this code: 我有以下代码:

if  (isset($_GET['file']) && isset($_GET['name']))
{

    $ch = curl_init($file);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);

    $data = curl_exec($ch);
    curl_close($ch);

    if (preg_match('/Content-Length: (\d+)/', $data, $matches)) 
    {
        // Contains file size in bytes
        $contentLength = (int)$matches[1];
    }

    header("Content-type: application/x-file-to-save");
    header("Content-Disposition: attachment; filename=".$_REQUEST['name']);
    header('Content-Length: ' . $contentLength);
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    header('Connection: Keep-Alive');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0', false);
    header('Cache-Control: private', false);

    readfile($file);
}

The problem is that $file is located on a different server. 问题是$ file位于另一台服务器上。 How do I enable resuming this download? 如何启用恢复此下载? Thanks! 谢谢!

Modify your curl to also pull in the body (remove the NOBODY option) 修改卷发使其也拉入身体(删除NOBODY选项)

You can then split the returned content ($data) into the header and the body - the split is the first blank line (look for two carriage returns in a row - the stuff above this is the header, anything below is the body). 然后,您可以将返回的内容($ data)拆分为标题和正文-拆分为第一行空白(连续查找两个回车符-上面的内容为标题,下面的内容为正文)。 Put them into variables $header and $body. 将它们放入变量$ header和$ body。

Run your preg_match on $header. 在$ header上运行您的preg_match。

To output the rest, simply "echo $body", or substr($body, $startpos) for a resumable download. 要输出其余内容,只需“ echo $ body”或substr($ body,$ startpos)即可恢复下载。


Resumable downloads: if the file is large, then you might want to cache it locally. 断点续传下载:如果文件很大,则可能要在本地缓存。 (ie save "$body" to a local file, and then use readfile on the local file. Then you can handle the resumable download by opening the file (fopen) and going to the right place (fseek) and reading (fread) / echoing (echo) the rest from there. fpassthru should do the same too, once you've found the starting point. (即,将“ $ body”保存到本地文件,然后在本地文件上使用readfile。然后,您可以通过打开文件(fopen)并转到正确的位置(fseek)并阅读(读取)来处理可恢复的下载/一旦找到起点,fpassthru也应该做同样的事情。

Also, if you're trying to pass off someone else's content as your own, get permission first ;) (otherwise why not simply direct the user to that other URL and save yourself the bandwidth in and out) 另外,如果您尝试假冒他人的内容,请先获得许可;)(否则为什么不直接将用户定向到该其他URL并节省带宽出入)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM