1

我有以下 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;}
}
4

1 回答 1

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();
于 2013-11-04T00:15:28.040 回答