如何通过php流式传输文件?另外,我需要将一些标题传递给远程文件。
伪代码:
End user (download zip) <-> http://localhost/script.php?downloadId=1 <-> http://example.com/file.zip
带标题:
Cache-Control: No-Cache
我尝试了自己的解决方案,但它让nginx服务器抛出了
504 Gateway Time-out
这是代码:
<?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;
?>
答案 0 :(得分:0)
使用readfile()
发送文件,header('Cache-Control: No-Cache')
发送标题。
官方PHP文档中的示例:
$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
有关更多替代方案,请查看Streaming a large file using PHP