Search code examples
phpmime

PHP: Why is this forced mime download adding 2 extra empty lines?


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!


Solution

  • 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);