Search code examples
phphtmlfopen

Why is there extra whitespace at the beginning of my file after I write it with PHP?


I am trying to make a PHP script which creates a file and adds headers into that file but the file must be PHP code only, with nothing before the PHP tags.

But for some reason, the script is adding an extra blank line and it does not work. I know this because when I manually edited it and removed the line it worked. Here is the script:

$stringData = "<?php\n
header('Content-type: audio/mp3');\n
\n
header('Content-Disposition: attachment; filename=\"$name\"');\n
readfile(\"$name.mp3\");\n
?>";

$myFile = "matt/$name/download.php";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);

Solution

  • Where is the blank line? If it's at the end of the file, the simplest solution is to remove the closing ?>.

    It is actually considered a best practice by many to omit the closing PHP tag in files that are meant to include only PHP code.

    Or, as an alternative, have you tried file_put_contents()?

    update

    There is no obvious way the code you've posted could result in leading whitespace; Passing 'w' to fopen truncates the file and you have no leading whitespace in the content you are writing afterwards. When I run your code, I get the desired output with no leading whitespace (and duplicate newlines as noted by codeaddict):

    <?php
    
    header('Content-type: audio/mp3');
    
    
    
    header('Content-Disposition: attachment; filename="test"');
    
    readfile("test.mp3");
    
    ?>