[英]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.