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

x4shl7ld  于 2023-03-16  发布在  PHP
关注(0)|答案(3)|浏览(234)

我已经设法找到,检索和保存一个文件使用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;

?>

谢谢你的帮助。

qco9c6ql

qco9c6ql1#

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

echo $data;

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

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

hrirmatl2#

考虑到你说的.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);
jobtbby3

jobtbby33#

您需要将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获取指导。

相关问题