0

How can I stream a file through php? Also I need to pass some headers to the remote file.

Pseudocode:

End user (download zip) <-> http://localhost/script.php?downloadId=1 <-> http://example.com/file.zip

With headers:

Cache-Control: No-Cache

I tried coming up with my own solution, but it makes the nginx server throw a

504 Gateway Time-out

Here's that code:

<?php
    set_time_limit(0);

    define('CHUNK_SIZE', 1024*1024);

    $url = "http://example.com/file.zip";

    $opts = array(
        'http'=>array(
            'method'=>"GET",
            'header'=>"Accept-language: en\r\n" .
                "Cache-Control: No-Cache\r\n" .
                "Connection: Keep-Alive\r\n"
        )
    );
    $context = stream_context_create($opts);
    stream_context_set_default($opts);

    $fp = fopen($url, 'r', false, $context);
    foreach (get_headers($url) as $header)
    {
        header($header);
    }

    //fpassthru($fp);

    while (!feof($fp)) {
        $buffer = fread($fp, CHUNK_SIZE);
        echo $buffer;
        ob_flush();
        flush();

        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }

    $status = fclose($fp);

    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }

    exit;
?>
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Ragnar Olsen
  • 56
  • 1
  • 7

1 Answers1

1

Use readfile() to send the file and header('Cache-Control: No-Cache') for the header.

Example from the official PHP documentation:

$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

http://php.net/manual/de/function.readfile.php

For more alternatives, have a look at Streaming a large file using PHP

Community
  • 1
  • 1
stmllr
  • 652
  • 3
  • 18