I have a PHP script I wrote to create a .txt tab delimited file. I need to have this forced downloaded to the web browser. It does all this, but when I compare the file to the source the forced downloaded on contain two extra blank lines. Here is the code:
// Force download of the tab del .txt file to the web browser:
header('Content-Type: application/download');
header("Content-Disposition: attachment; filename=$tab_del_file");
header("Content-Length: " . filesize($tab_del_file));
$fp = fopen($tab_del_file, "r");
fpassthru($fp);
fclose($fp);
Linux Shell Command to compare the two files and show there are extra blank lines: $ diff example.txt /tmp/example.txt 25a26,27
I sftp'ed the downloaded example.txt to the /tmp directory so I could then do the diff on the server. Why are two blank lines being added to the downloaded version and what is the fix? Thanks!
As the php code itself looks ok and does not produce that new lines, this can have only one reason. You have a closing ?> tag and extra new lines at the end of your file:
?>
<--- empty line
<--- empty line
Note the content outside the php tags will not be parsed by PHP and just forwarded to the browser.
Solution: remove the closing ?> tag or the extra new lines. I usually prefer just not using the ?>
Btw, I should mention that this:
$fp = fopen($tab_del_file, "r");
fpassthru($fp);
fclose($fp);
can be simplified by
readfile($tab_del_file);
You most likely have an extra blank line after the closing ?>, which is being echoed with the data. The closing ?> is always optional at the end of a PHP file. Leaving it out is a good practice to prevent this sort of problem.
Actually this is problem due to position of php closing Tag.. ?>.
Basically the PHP closing tag on a PHP document ?> is optional to the PHP parser. So if it is used in your script and you leave any whitespace after ?> then it can cause unwanted error or output. I believe In your case also you would have done the same mistake.
So for this reason, PHP script should OMIT the closing Tag and instead you should use a comment block to mark the end of script.
Here is small example:
INCORRECT:
<?php
echo "Hello World!";
?>
CORRECT:
<?php
echo "Hello World!";
/* End of file myfile.php */
/* Location: ./system/modules/mymodule/myfile.php */
I Hope this helps you..!!
来源:https://stackoverflow.com/questions/16372678/php-why-is-this-forced-mime-download-adding-2-extra-empty-lines