readfile
(PHP 4, PHP 5, PHP 7, PHP 8)
readfile — 輸出檔案
說明
readfile(string
$filename
, bool $use_include_path
= false
, resource $context
= ?): int讀取檔案並寫入到輸出緩衝。
參數
-
filename
-
要讀取的檔名。
-
use_include_path
-
想要在 include_path 中搜索檔案,可使用這個可選的第二個參數,設為
true
。 -
context
-
Stream 上下文(context) resource。
返回值
成功時返回從檔案中讀入的位元組數, 或者在失敗時返回 false
錯誤/異常
失敗時拋出E_WARNING
警告。
範例
示例 #1 使用 readfile() 強制下載
<?php
$file = 'monkey.gif';
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;
}
?>
以上例程的輸出類似於:

註釋
注意:
readfile() 自身不會導致任何記憶體問題。 如果出現記憶體不足的錯誤,使用 ob_get_level() 確保輸出快取已經關閉。
小技巧
如已啟用fopen 包裝器,在此函式中, URL 可作為檔名。關於如何指定檔名詳見 fopen()。各種 wapper 的不同功能請參見 支援的協議和封裝協議,注意其用法及其可提供的預定義變數。
上下文流(context stream) resource。
參見
- fpassthru() - 輸出檔案指針處的所有剩餘數據
- file() - 把整個檔案讀入一個陣列中
- fopen() - 打開檔案或者 URL
- include - include
- require - require
- virtual() - 執行 Apache 子請求
- file_get_contents() - 將整個檔案讀入一個字串
- 支援的協議和封裝協議