Search code examples
phpfopenreadfilefwritefclose

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


<?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:

25Who let the dogs out?!

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.


Solution

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