简体   繁体   中英

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. How do I enable resuming this download? Thanks!

Modify your curl to also pull in the body (remove the NOBODY option)

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). Put them into variables $header and $body.

Run your preg_match on $header.

To output the rest, simply "echo $body", or substr($body, $startpos) for a resumable download.


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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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