站內搜尋

Monday, September 29, 2014

[PHP] 淺談 readfile() 與 fread() 的用法差異 (在下載檔案時)

如果我們要把 PHP處理好的數據,寫到 txt 檔案中,語法如下:

$temptxtfile = 'temptxtfile.txt';

$fp = fopen($temptxtfile, 'a');
fputs($fp, '123');
fclose($fp);

如果要讓 user 下載,官網的作法是採用readfile(),如下:
header("Content-type: application/text");
header('Content-Disposition: attachment; filename="my.txt"');
readfile($temptxtfile);

如果我們需要丟到一個變數中(如:$html),然後再 echo 出來時,方法如下:
header("Content-type: application/text");
header('Content-Disposition: attachment; filename="my.txt"');
$h = fopen($temptxtfile, 'r');
$html = fread($h, filesize($temptxtfile));
echo $html;

差別在於,如果用 $html = readfile($temptxtfile),則會取得$temptxtfile這個檔案的位元數,而這並不是 user 要的。

No comments:

Post a Comment