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

如何使用php将文件输出到浏览器?,php,curl,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); cu

我已经使用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;


?>


谢谢您的帮助。

因为您已经有了要发送到浏览器的数据,只需打印或回显即可

echo $data;
要使浏览器显示下载框,需要设置正确的标题():

您需要发送到浏览器。
在文档中,有一个关于它的示例:

示例#1下载对话框

如果希望提示用户保存正在发送的数据, 如生成的PDF文件,您可以使用»内容处置 标头以提供建议的文件名并强制浏览器 显示“保存”对话框


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

什么类型的文件?@JayBlanchard任何文件(可以是.zip;.exe或rar)都不能将这些文件类型输出到浏览器。你是说让该文件可供下载吗?为什么不在问题中添加一个完整的解释,而不是重复“谢谢你的帮助”(无论如何不应该在那里)来绕过问题质量过滤器?而不是一般的复制粘贴引用,你可以编辑你的代码来匹配他的变量和数据吗?这应该是公认的答案,谢谢@难以置信什么假设?他的第一句话是:“我用CURL找到、检索和保存了一个文件。”。。。保存文件。就像你假设我假设他在保存文件一样?没有假设,只是从他提供的情景上下文推断。我给出了一个解决方案,如果他不能弄清楚
$filepath
以及如何正确使用变量,我认为他有更多的问题,那就是不使用
目标
。这不是一个教学网站,Geezus,随便什么。走开。
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);