fread

(PHP 4, PHP 5, PHP 7, PHP 8)

fread讀取文件(可安全用于二進(jìn)制文件)

說明

fread(resource $handle, int $length): string

fread() 從文件指針 handle 讀取最多 length 個(gè)字節(jié)。 該函數(shù)在遇上以下幾種情況時(shí)停止讀取文件:

  • 讀取了 length 個(gè)字節(jié)
  • 到達(dá)了文件末尾(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.

參數(shù)

handle

文件系統(tǒng)指針,是典型地由 fopen() 創(chuàng)建的 resource(資源)。

length

最多讀取 length 個(gè)字節(jié)。

返回值

返回所讀取的字符串, 或者在失敗時(shí)返回 false

范例

示例 #1 一個(gè)簡(jiǎn)單的 fread() 例子

<?php
// get contents of a file into a string
$filename "/usr/local/something.txt";
$handle fopen($filename"r");
$contents fread($handlefilesize($filename));
fclose($handle);
?>

示例 #2 Binary fread() example

警告

在區(qū)分二進(jìn)制文件和文本文件的系統(tǒng)上(如 Windows)打開文件時(shí),fopen() 函數(shù)的 mode 參數(shù)要加上 'b'。

<?php
$filename 
"c:\\files\\somepic.gif";
$handle fopen($filename"rb");
$contents fread($handlefilesize($filename));
fclose($handle);
?>

示例 #3 Remote fread() examples

警告

當(dāng)從任何不是普通本地文件讀取時(shí),例如在讀取從遠(yuǎn)程文件popen() 以及 fsockopen() 返回的流時(shí),讀取會(huì)在一個(gè)包可用之后停止。這意味著應(yīng)該如下例所示將數(shù)據(jù)收集起來合并成大塊。

<?php
// 對(duì) PHP 5 及更高版本
$handle fopen("http://www.example.com/""rb");
$contents stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle 
fopen("http://www.example.com/""rb");
$contents '';
while (!
feof($handle)) {
  
$contents .= fread($handle8192);
}
fclose($handle);
?>

注釋

注意:

如果只是想將一個(gè)文件的內(nèi)容讀入到一個(gè)字符串中,用 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() - 寫入文件(可安全用于二進(jìn)制文件)
  • fopen() - 打開文件或者 URL
  • fsockopen() - 打開一個(gè)網(wǎng)絡(luò)連接或者一個(gè)Unix套接字連接
  • popen() - 打開進(jìn)程文件指針
  • fgets() - 從文件指針中讀取一行
  • fgetss() - 從文件指針中讀取一行并過濾掉 HTML 標(biāo)記
  • fscanf() - 從文件中格式化輸入
  • file() - 把整個(gè)文件讀入一個(gè)數(shù)組中
  • fpassthru() - 輸出文件指針處的所有剩余數(shù)據(jù)
  • ftell() - 返回文件指針讀/寫的位置
  • rewind() - 倒回文件指針的位置