PHP text file has numbers in front when downloaded + unexpected file name

时间:2021-07-02 10:07:48
<?php
$file = fopen("testing.txt","w");
$txt = "Who let the dogs out?! \r\n";
echo fwrite($file, $txt);

header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file.txt");
header("Content-Type: text/plain; ");
header("Content-Transfer-Encoding: binary");

readfile('testing.txt');
?>

First issue: I read on the PHP website (http://php.net/manual/en/function.fopen.php) that there could be issues with line-ending, but when testing.txt has been downloaded and is opened, the following line appears with some numbers added in front:

第一个问题:我在PHP网站(http://php.net/manual/en/function.fopen.php)上读到可能存在行尾的问题,但是当下载并打开testing.txt时,出现以下行,前面添加了一些数字:

25Who let the dogs out?!

25Who让狗出去?!

Second issue: I noticed the file name is Resource id #3.txt instead of testing.txt. A Google search reveals that that error message is commonly associated with MySQL/PHP, but it is only PHP for my case.

第二个问题:我注意到文件名是Resource id#3.txt而不是testing.txt。 Google搜索显示该错误消息通常与MySQL / PHP相关联,但对于我的情况,它只是PHP。

1 个解决方案

#1


1  

I guess, it is because you have this line in your code

我想,这是因为你的代码中有这一行

echo fwrite($file, $txt);

Try this code

试试这个代码

fwrite($file, $txt);

and correct this

并纠正这一点

$filename = 'testing.txt';
header("Content-Disposition: attachment; filename=$filename.txt");

#1


1  

I guess, it is because you have this line in your code

我想,这是因为你的代码中有这一行

echo fwrite($file, $txt);

Try this code

试试这个代码

fwrite($file, $txt);

and correct this

并纠正这一点

$filename = 'testing.txt';
header("Content-Disposition: attachment; filename=$filename.txt");