开发者

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: a开发者_Python百科ttachment; 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);


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

?>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜