fread
(PHP 4, PHP 5, PHP 7, PHP 8)
fread — 讀取檔案(可安全用於二進制檔案)
說明
$stream
, int $length
): string|false
fread() 從檔案指針
stream
讀取最多
length
個位元組。
該函式在遇上以下幾種情況時停止讀取檔案:
-
讀取了
length
個位元組 - 到達了檔案末尾(EOF)
- a packet becomes available or the socket timeout occurs (for network streams)
- if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.
返回值
返回所讀取的字串, 或者在失敗時返回 false
。
範例
示例 #1 一個簡單的 fread() 例子
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
示例 #2 Binary fread() example
在區分二進制檔案和文字檔案的系統上(如 Windows)打開檔案時,fopen() 函式的 mode 參數要加上 'b'。
<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
示例 #3 Remote fread() examples
當從任何不是普通本地檔案讀取時,例如在讀取從遠端檔案或 popen() 以及 fsockopen() 返回的流時,讀取會在一個包可用之後停止。這意味著應該如下例所示將數據收集起來合併成大塊。
<?php
$handle = fopen("http://www.example.com/", "rb");
if (FALSE === $handle) {
exit("Failed to open stream to URL");
}
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>
註釋
注意:
如果只是想將一個檔案的內容讀入到一個字串中,用 file_get_contents(),它的效能比上面的程式碼好得多。
注意:
Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.
參見
- fwrite() - 寫入檔案(可安全用於二進制檔案)
- fopen() - 打開檔案或者 URL
- fsockopen() - 打開一個網路連線或者一個Unix套接字連線
- popen() - 打開程序檔案指針
- fgets() - 從檔案指針中讀取一行
- fgetss() - 從檔案指針中讀取一行並過濾掉 HTML 標記
- fscanf() - 從檔案中格式化輸入
- file() - 把整個檔案讀入一個陣列中
- fpassthru() - 輸出檔案指針處的所有剩餘數據
- fseek() - 在檔案指針中定位
- ftell() - 返回檔案指針讀/寫的位置
- rewind() - 倒回檔案指針的位置
- unpack() - Unpack data from binary string