函式名稱:php://()
適用版本:所有版本
函式描述:php:// 是一個封裝協議(wrapper protocol),可以用於訪問各種輸入/輸出流,如檔案、網路連線、標準輸入/輸出等。它提供了一種統一的方式來處理不同型別的流。
用法: php:// 的一般格式為 php://wrapper/resource,其中 wrapper 是協議部分,resource 是具體的資源。
以下是一些常見的用法及示例:
- 讀取檔案內容:
$file = fopen('php://filter/read=string.strip_tags/resource=path/to/file.txt', 'r');
while (!feof($file)) {
echo fgets($file);
}
fclose($file);
上述示例中,我們使用了 php://filter 協議來讀取檔案內容,並使用 string.strip_tags 過濾器去除檔案中的 HTML 標籤。
- 寫入資料到檔案:
$file = fopen('php://output', 'w');
fwrite($file, 'Hello, world!');
fclose($file);
上述示例中,我們使用了 php://output 協議來將資料寫入到標準輸出。
- 讀取 POST 請求資料:
$input = file_get_contents('php://input');
$data = json_decode($input, true);
上述示例中,我們使用了 php://input 協議來獲取 POST 請求的原始資料,並將其解析為 JSON 格式。
- 讀取遠端檔案內容:
$file = fopen('php://temp', 'r+');
$remoteFile = fopen('php://input', 'r');
stream_copy_to_stream($remoteFile, $file);
fclose($remoteFile);
rewind($file);
while (!feof($file)) {
echo fgets($file);
}
fclose($file);
上述示例中,我們使用了 php://temp 協議來建立一個臨時檔案,並使用 php://input 協議來讀取遠端檔案內容,並將其複製到臨時檔案中。
總結:php://() 是一個非常強大的函式,它提供了訪問各種輸入/輸出流的靈活方式。透過不同的協議和資源引數的組合,我們可以實現檔案讀寫、網路連線、資料過濾等各種操作。需要根據具體的需求來選擇合適的協議和資源引數。