[英]Download a pdf file using PHP with a search form
我创建了一个搜索表单,用户可以在其中输入图像代码,并且在搜索时可以让用户下载文件。 下面是我的代码
<html>
<head>
<title>Search Contacts</title>
</head>
<body>
<h3>Search Client File</h3>
<form method="post" action="#" id="searchform">
Type the File Code:<br><br>
<input type="text" name="fcode">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$filecode=$_POST["fcode"];
if (!empty($filecode))
{
$file="/var/www/website/$filecode.pdf";
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
}
else
{
echo "No Results";
}
?>
</body>
</html>
问题是下载的文件无法查看或无法查看,我的代码似乎是什么问题?
尝试更改此标头:
header('Content-Type: application/pdf');
您的代码将永远无法工作。 您将在每次执行代码时开始输出HTML表单。 如果请求下载,下载将被附加到该HTML页面。 并且header()
调用也将因“ headers has sent”而失败。
如果您要将表单提交到同一页面,则需要先下载代码:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... download stuff here
exit(); // critical - don't let the html get output
}
... html form here ...
我已经使其正常工作,下面是供参考的代码。
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
ob_end_flush();
readfile($file);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.