PHP readfile 基本上是 PHP 庫中的內建函數,用於讀取檔案然後將其寫入輸出緩衝區。
開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
文法:
readfile ( string $file_name [, boolean $path = FALSE [, resource $context ]] ) : int
語法中使用的參數:
除了 readfile() 函數之外,以下是一些可用來對檔案執行各種操作的其他函數。
此函數也用於讀取文件,它將完整的文件讀取到陣列中。
文法:
file ( string $file_name [, int $flag = 0 [, resource $context ]] ) : array
其中file_name是要讀取的檔案的路徑。標誌是可選字段,可以從以下常數中選擇:
成功時傳回數組中存在的文件,失敗時傳回 false。
此函數可用於開啟文件和 URL。
fopen ( string $file_name , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource
模式:此參數提到了需要授予流的存取權限類型。以下是一些重要的模式:
如果成功則傳回檔案指標資源,如果失敗則傳回 false。
此函數用於二進位安全檔案讀取。
文法:
fread ( resource $handle , int $length ) : string
句柄用來引用檔案指標。
檔案將被讀取,直到達到以下條件之一:長度(以位元組為單位)必須已讀取、達到 EOF、發生套接字逾時。 fgets()、fscanf()、ftell()、fwrite()、fopen()、fsockopen() 是 PHP 中用於檔案操作的其他一些函數。
下面給的是 PHP 讀取檔的範例:
代碼:
輸出:
這顯示了讀取本機路徑中存在的檔案的基本範例。確保建立了 readfile() 函數參數中指定的檔案名,並且要讀取的內容存在於檔案內。當使用 readfile() 函數時,它會讀取檔案的內容並在輸出中列印。
代碼:
輸出:
之前的輸出是一個沒有任何條件的簡單範例。在此範例中,讓我們看看如何使用某些條件讀取並顯示檔案的輸出。我們使用 if 語句來列印假設檔案不存在。
代碼:
輸出:
In this example, we are combining the use of multiple file read functions. As in all the above examples, first, we are giving the file name which needs to be read from. Then the mode of operation, ‘r’ is given to them indicating it can only be read. filesize() function takes the filename and returns the size of the file along with its data and assigns it to $data variable. By using fclose() function we are closing that file. Finally, the data is printed as output.
Code:
Output:
Before running the code, make sure that the file to be read file.txt is created in the local file path. In this example first, we are declaring the file name to be read and opening that with the function fopen(). Suppose the file does not exist, using if condition we are throwing an error message. Finally, we are printing the file size and the content present in the input file.
As seen from all the above examples, readfile() is one of the main functions of PHP used for reading the file name specified in this function. Apart from readfile() we have covered a few other file operations which perform similar actions such as fopen, file, fread, fgets, fgetss, ftell, etc. A combination of all of these are basically used in accessing and performing operations on the input file.
以上是PHP讀取文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!