我有以下PHP代码使用标头从服务器下载文件:
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
这段代码工作正常,但是我把它放在一个带有HTML表单的文件中,并使用if isset运行所有HTML代码放在文件中,以及我在PHP中回显的任何内容;我最终想要的文件就在那里。
我无法弄清楚标题中的内容是什么导致它在下载时将屏幕上的所有内容写入文件。他服务器上的文件没有改变,应该如何。
感谢您的帮助。
下载所有代码......
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post"><br>
Order Number: <input type="number" name="orderNo" size="10"/>
<input type="submit" name="Download" value="Download" />
</form>
</body>
</html>
<?php
if(isset($_POST['Download'])){download();}
function download()
{
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('amazondb', $conn);
$result = mysql_query("SELECT ID, PurchaseDate, BuyerName, ShipCity, ShipState, ShipPostalCode, ShipCountry,
ShipAddress1, ShipAddress2, ShipAddress3 FROM imported_orders");
$orderNo = $_POST['orderNo'];
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($orderNo>0&&$orderNo<=count($row))
{
$file = fopen('Order.txt', 'w');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if($row['ID']==($orderNo))
{
echo "Hello";
fwrite($file, $row['BuyerName'].PHP_EOL .$row['ShipAddress1'].PHP_EOL .$row['ShipAddress2'].PHP_EOL .$row['ShipAddress3'].PHP_EOL .$row['ShipCity'].PHP_EOL .$row['ShipState'].PHP_EOL .$row['ShipPostalCode'].PHP_EOL .$row['ShipCountry'].PHP_EOL);
}
}
fclose($file);
$file = 'Order.txt';
header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
else{echo "Please enter a valid Order Number"; echo $orderNo;}
}
答案 0 :(得分:1)
在文件的开头移动此代码,因此您将拥有:
<?php
if (your condition to output file) {
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
die();
}
the rest of your file....
另一个解决方案,位于文件的最顶部:
<?php
ob_start() or die('Cannot start output buffering');
... your page
在第一个header
添加之前:
$file = 'Order.txt';
ob_end_clean();
header("Cache-Control: public");
...
readfile($file);
die();