readfile
(PHP 4, PHP 5, PHP 7)
readfile — 輸出文件
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
讀取文件並寫入到輸出緩衝。
參數名 | 說明 |
---|---|
filename | 要讀取的文件名。 |
use_include_path | 想要在 include_path 中搜索文件,可使用這個可選的第二個參數,設爲 TRUE。 |
context | Stream 上下文(context) resource。 |
返回值
返回從文件中讀入的字節數。如果出錯返回 FALSE 並且除非是以 @readfile() 形式調用,否則會顯示錯誤信息。
學習readfile函數的用法後,就可以實現文件下載咯
//文件下載
$file = 'monkey.jpg';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
註釋
Note:
readfile() 自身不會導致任何內存問題。 如果出現內存不足的錯誤,使用 ob_get_level() 確保輸出緩存已經關閉。
Note: 在 PHP 5.0.0 中增加了對上下文(Context)的支持。有關上下文(Context)的說明參見 Streams。