函式名稱:fopen()
適用版本:所有PHP版本
用法:fopen() 函式用於開啟一個檔案或者 URL,並返回一個資源控制代碼,用於後續的檔案讀寫操作。
語法:resource fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] )
引數:
- $filename:要開啟的檔名或者 URL。
- $mode:開啟檔案的模式。可以是以下幾種模式之一:
- "r":只讀方式開啟,從檔案頭開始。
- "w":寫入方式開啟,將檔案內容截斷為零長度,如果檔案不存在則嘗試建立。
- "a":寫入方式開啟,將檔案指標指向檔案末尾,如果檔案不存在則嘗試建立。
- "x":建立並以寫入方式開啟,如果檔案已存在,則 fopen() 失敗並返回 FALSE。
- "b":以二進位制模式開啟檔案。
- "t":以文字模式開啟檔案。
- "r+":讀寫方式開啟,從檔案頭開始。
- "w+":讀寫方式開啟,將檔案內容截斷為零長度,如果檔案不存在則嘗試建立。
- "a+":讀寫方式開啟,將檔案指標指向檔案末尾,如果檔案不存在則嘗試建立。
- "x+":建立並以讀寫方式開啟,如果檔案已存在,則 fopen() 失敗並返回 FALSE。
- $use_include_path(可選):如果設定為 TRUE,則在 include_path 中搜尋檔案。
- $context(可選):可以透過傳遞一個上下文資源來設定流的引數。
返回值:如果成功,則返回一個檔案資源控制代碼;如果失敗,則返回 FALSE。
示例:
- 開啟一個檔案並讀取內容:
$file = fopen("example.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
}
- 開啟一個檔案並寫入內容:
$file = fopen("example.txt", "w");
if ($file) {
fwrite($file, "Hello, World!");
fclose($file);
}
- 開啟一個URL並讀取內容:
$file = fopen("https://www.example.com", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
}
注意事項:
- 在使用完檔案資源後,應該使用 fclose() 函式關閉檔案控制代碼,以釋放系統資源。
- 如果 fopen() 失敗,則可能是由於檔案許可權問題、檔案不存在或者 URL 訪問錯誤等原因。