質問

I'm working on a small piece of code that takes a specific record from an SQL table and places certain columns from that record in a txt file. This works fine, however if I try to echo something to screen, after or before where I fopen the file or fwrite it places that echo in the file as well, even text outside the is placed in the file.

Here is my current code in its' entirety:

Even this outside the PHP is placed in the file.
<?php
echo "Banana";

$orderNo = 3;
    //DB Connect
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('amazondb', $conn); 
    //Open file, select Table
$file = fopen('upload/Order.txt', 'w');
$result = mysql_query("SELECT ID, PurchaseDate, BuyerName, BuyerPhoneNumber, 
                          BuyerEmail, ShipAddress1,          ShipAddress2, ShipAddress3 
                          FROM imported_orders"); 
    //Loop, input to file
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
{   if($row['ID']==($orderNo-1))
{fwrite($file, $row['PurchaseDate'].PHP_EOL .$row['BuyerName']);}
}
fclose($file);
    //Download File
$filename = "upload/Order.txt"; 
header("Content-Length: " . filesize($filename)); 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename=Order.txt'); 
readfile($filename);
?>

The above code outputs the following to file:

Even this outside the PHP is placed in the file.
Banana2013-03-14
name

This is my first time using headers and doing any form of download with PHP, so unsure if that is causing an issue. (I'll be having the download triggered via a HTML form using if isset and the "$orderNo" in the code will be input by the user, not sure if having that done now will solve this issue, though the fact it writes stuff even outside of the PHP worries me)

I open the file, write to the file, then close it, yet the echo before I even open the file is being written to it, same goes for having an echo after I close it.

This is really weird to me and makes no sense, though there is probably a simple explanation.

Edit: Only the file downloaded has the extra stuff in it, the file saved on the server is just the data from the table as intended.

役に立ちましたか?

解決

The way you use your headers now, all output will be put in the download. If you want a webpage with a link to a download, then create a second page with the link, linking to this page. Then on this page, only echo the data that you want in your file.

Basically what you say with the header is, everything that is sent to the browser for this request will be a file that you want to download.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top