PHP – read file

Loading

要如何透過 PHP 來讀取 Linux 下檔案.

測試環境為 CentOS 7 虛擬機 (IP: http://192.168.95.205) , Apache 安裝設定請參考 https://benjr.tw/323 , 如果使用 Nginx (Web server) 請參考 – https://benjr.tw/95761 與 PHP-FPM – https://benjr.tw/95767

使用 Ubuntu 16.04 x86_64 設定 Apache2 請參考 https://benjr.tw/95861 , web server 為 Nginx 請參考 https://benjr.tw/96633 .

參考文章 – https://www.w3schools.com/php/php_file_open.asp

fopen() , fread() , fclose()

透過下面三個函數來開啟,讀取,關閉檔案.

  • fopen() – Opens file or URL
    fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource
    開啟檔案模式如下.

    A list of possible modes for fopen() using mode
    mode Description
    ‘r’ Open for reading only; place the file pointer at the beginning of the file.
    ‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
    ‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
    ‘w+’ Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
    ‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
    ‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
    ‘x’ Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
    ‘x+’ Create and open for reading and writing; otherwise it has the same behavior as ‘x’.
    ‘c’ Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’), nor the call to this function fails (as is the case with ‘x’). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock()) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
    ‘c+’ Open the file for reading and writing; otherwise it has the same behavior as ‘c’.
    ‘e’ Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

    參考網頁 – http://php.net/manual/en/function.fopen.php

  • fread() – Binary-safe file read
    fread ( resource $handle , int $length ) : string
    不指定路徑時以當下 PHP 檔案路徑,通常在 Apache HTTP Root : /var/www/html .
    CentOS / RHEL Apache 執行 PHP 時使用 apache 這個使用者 (Ubuntu 則為 www-data),無法讀取 Linux 上所有的檔案 (權限限制使得執行失敗)
  • fclose() – Closes an open file pointer
    close ( resource $handle ) : bool
[root@localhost html]# cat test.txt
********************<br/>
*PHP Read File Code*<br/>
********************<br/>
File Reading sample<br/>
[root@localhost html]# cat fread.php 
PHP Code
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("test.txt"));
fclose($myfile);

or die() – or 的用法跟 Linux bash script 的 cmd1 || cmd2 一樣 ,若 cmd1 執行正確且無錯誤,則 cmd2 不執行 ,反之若 cmd1 執行完畢且為錯誤,則開始執行 cmd2.
會有下列的兩種情況.
若 fopen(“test.txt”, “r”) 執行正確且無錯誤就結束.
若 fopen(“test.txt”, “r”) 執行失敗就執行 die(“Unable to open file!”) (die 等同 exit – http://php.net/manual/en/aliases.php )- 顯示訊息並跳出程式.

執行結果

********************
*PHP Read File Code*
********************
File Reading sample

fgets() , feof()

相較於剛剛的 fread 會把整篇文章內容讀取出來,fgets 只會一次讀取一行並把檔案指標往下移.feof 可以用來確認檔案指標是否到最後.

  • fgets() – Gets a line from file pointer
    fgets ( resource $handle [, int $length ] ) : string
  • feof() — Tests for end-of-file on a file pointer
    feof ( resource $handle ) : bool
[root@localhost html]# vi fgets.php
<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}
fclose($myfile);
?> 

執行結果

********************

*PHP Read File Code*

********************

File Reading sample

fgetc()

fgetc 是一次只讀一個字元,然後把檔案指標往下一個字元移動.

  • fgetc — Gets character from file pointer
    fgetc ( resource $handle ) : string
[root@localhost html]# vi fgetc.php
<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
  echo fgetc($myfile);
}
fclose($myfile);
?>

執行結果

********************
*PHP Read File Code*
********************
File Reading sample

readfile()

不需要透過 fopen() 與 fclose() ,可以讀取顯示檔案內容並回傳檔案字元數總數.

  • readfile — Outputs a file
    readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] ) : int
[root@localhost html]# vi readfile.php
<?php
echo readfile("test.txt");
?>

執行結果

********************
*PHP Read File Code*
********************
File Reading sample
103

更多檔案讀取的指令請參考官方網站說明 – http://php.net/manual/en/ref.filesystem.php

沒有解決問題,試試搜尋本站其他內容

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料