1. 程式人生 > 實用技巧 >php fopen函式

php fopen函式

php中沒有單獨的檔案建立函式,如果我們想建立函式,可以使用fopen(),fopen()函式字面意思是開啟檔案,但該函式也有建立檔案的功能,當使用 fopen() 函式開啟一個檔案時,如果檔案不存在,則會嘗試建立該檔案,並返回一個資源。

php fopen函式介紹

fopen函式開啟檔案或者 URL

語法:

resource fopen( string filename, string mode )

fopen()將 filename 指定的名字資源繫結到一個流上。

引數:

1. filename為嘗試開啟/建立的檔名。

如果 filename 是 "scheme://..." 的格式,則被當成一個 URL,PHP 將搜尋協議處理器(也被稱為封裝協議)來處理此模式。如果該協議尚未註冊封裝協議,PHP 將發出一條訊息來幫助檢查指令碼中潛在的問題並將 filename 當成一個普通的檔名繼續執行下去。

如果 PHP 認為 filename 指定的是一個本地檔案,將嘗試在該檔案上開啟一個流。該檔案必須是 PHP 可以訪問的,因此需要確認檔案訪問許可權允許該訪問。如果激活了安全模式或者 open_basedir 則會應用進一步的限制。

如果 PHP 認為 filename 指定的是一個已註冊的協議,而該協議被註冊為一個網路 URL,PHP 將檢查並確認 allow_url_fopen 已被啟用。如果關閉了,PHP 將發出一個警告,而 fopen 的呼叫則失敗。

2. mode 指定了開啟模式,其可能的值如下:

開啟模式說明
r 只讀,並將檔案指標指向檔案開始位置
r+ 讀寫,將檔案指標指向檔案開始位置
w 只寫,將檔案指標指向檔案開始位置並將檔案內容清空,如果檔案不存在則嘗試建立之
w+ 讀寫,將檔案指標指向檔案開始位置並將檔案內容清空,如果檔案不存在則嘗試建立之
a 追加,將檔案指標指向檔案末尾來操作,如果檔案不存在則嘗試建立之
a+ 讀寫追加,將檔案指標指向檔案末尾來操作,如果檔案不存在則嘗試建立之
x 只寫,並建立檔案,如果檔案已存在,則 fopen() 呼叫失敗並返回 FALSE
x+ 讀寫,並建立檔案,如果檔案已存在,則 fopen() 呼叫失敗並返回 FALSE

php fopen函式例項

1、使用fopen函式建立檔案:

1 2 $my_file = 'file.txt';//如果檔案不存在(預設為當前目錄下) $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file

2、使用fopen函式開啟檔案:

1 2 $my_file = 'file.txt';//假設檔案file.txt存在 $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //open file for writing ('w','r','a')...

3、fopen函式結合fread讀取檔案:

1 2 3 $my_file = 'file.txt'; $handle = fopen($my_file, 'r'); $data = fread($handle,filesize($my_file));

4、fopen函式結合fwrite函式寫檔案

1 2 3 4 $my_file = 'file.txt'; $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); $data = 'This is the data'; fwrite($handle, $data);

5、fopen函式結合fwrite函式向檔案中追加內容:

1 2 3 4 5 6 $my_file = 'file.txt'; $handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file); $data = 'New data line 1'; fwrite($handle, $data); $new_data = "\n".'New data line 2'; fwrite($handle, $new_data);

6、fopen() 函式還可用於開啟網際網路上的 URL 地址:

1 2 3 4 5 6 7 8 <?php $fh = fopen("http://www.baidu.com/", "r"); if($fh){ while(!feof($fh)) { echo fgets($fh); } } ?>

注意:fopen() 返回的只是一個資源,要想顯示開啟的頁面地址,還需要用 fgets() 函式讀取並輸出。