如何用php输出文件到浏览器?

时间:2018-02-05 17:41:31

标签: php curl

我已设法使用CURL查找,检索和保存文件。现在我想用php输出文件到浏览器。

<?php 
$url = 'http://example.com/downloadshort/5941';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);

// show header on the response
curl_setopt($ch, CURLOPT_HEADER, 1);

$data = curl_exec ($ch);

// get size of header
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
// take header part from response
$header = substr($data, 0, $header_size);
// delete header part from data variable
$data   = substr($data, $header_size+1);

$error = curl_error($ch); 
curl_close ($ch);

// get file name and extension from header
preg_match('~filename=(.*)\.([\S]+)~i', $header, $f);
list($dummy, $filename, $ext)       = $f;


$destination = $filename.'.'.$ext;


?>

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

由于您已经拥有要发送到浏览器的数据,只需printecho

echo $data;

要让浏览器显示下载框,您需要设置正确的标题(MDN):

header('Content-Disposition: attachment; filename="' . $filename . '"');

答案 1 :(得分:0)

您需要将header发送到浏览器 在文档中,有一个例子:

  

示例#1下载对话框

     

如果您希望系统提示用户保存您要发送的数据,   例如生成的PDF文件,您可以使用»Content-Disposition   标头提供推荐的文件名并强制浏览器   显示保存对话框。

     
<?php
// We'll be outputting a PDF
header('Content-Type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>
在您设置正确的标题后

,将readfile('original.pdf');更改为print $data;

在您的代码中,您有$ext个文件变量,Content-Type标题需要更具体:请参阅Media_type

答案 2 :(得分:0)

考虑到你说.zip,.exe等,我假设你想要能够显示文件,这意味着能够下载它...如果是这样的话:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filepath));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
ob_clean();
flush();
readfile($filepath);