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;
?>