(PHP 3, PHP 4, PHP 5)
fread() 從檔案指標 handle 讀取最多 length 個位元組。該函數在讀取完 length 個位元組數,或到達 EOF 的時候,或(對於網路流)當一個包可用時就會停止讀取檔案,視乎先碰到哪種情況。
<?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);?>
在區分二進位檔案和文字檔案的系統上(如 Windows)開啟檔案時,fopen() 函數的 mode 參數要加上 'b'。
<?php$filename = "c:\\files\\somepic.gif";$handle = fopen($filename, "rb");$contents = fread($handle, filesize ($filename));fclose($handle);?>
當從網路流或是管道讀取時,例如在讀取從遠端檔案或 popen() 以及 proc_open() 的返回時,讀取會在一個包可用之後停止。這意味著應該如下例所示將資料收集起來合併成大塊。
<?php$handle = fopen ("http://www.example.com/", "rb");$contents = "";while (!feof($handle)) { $contents .= fread($handle, 8192);}fclose($handle);?>
注: 若果只是想將一個檔案的內容讀入到一個字串中,用 file_get_contents(),它的效能比上面的代碼好得多。
參見 fwrite(),fopen(),fsockopen(),popen(),fgets(),fgetss(),fscanf(),file() 和 fpassthru()。