views:

82

answers:

2

Hello there,
I am trying to make my PHP script create a file and add headers into that file but the file must be PHP only and nothing before the PHP tags.

But the script is for some reason adding an extra blank line in the beginning before the <?php and it does not work. I know this because when I manually edited it and removed the line it worked. Here is the script and thanks a lot:

$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);
+1  A: 

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

?>
meagar
its in the beginning.
Matthew Carter
Worked like a charm.
Matthew Carter
I think what the problem was is that i had a line break before the `<?php` and when i fixed it google chrome was loading a cached version thanks though this worked great
Matthew Carter
@Matthew What did, `file_put_contents`? That's very odd, as it should have been identical to the `fopen` code you were using
meagar
@MC *Worked like a charm* means you are supposed to accept that answer (and maybe even up-vote it if you like...). Btw, how do you know the line was before or after the `<php` tag? It is very likely it was after the closing `?>`.
ring0
A: 

You are using \n and also writing the contents on different lines, hence creating two newlines.

Example:

echo "a\n
b";

Will print

a

b

Remove either the \n or the line breaks to fix this.

codaddict
its in the beginning
Matthew Carter
before the `<?php` tag
Matthew Carter
I don't think the code you've shown us can do that. please cross check.
codaddict
well when i visit the site it throws an error and when i manually open it in Dreamweaver there is a line break before the first tag.
Matthew Carter
What error does it throw?
Matt Gibson