Streams 是 PHP 核心內建的統一資源存取層,將檔案、網路、壓縮、記憶體等不同資源抽象為一致的資料流介面,提供 fopen()、fread()、fwrite()、stream_get_contents() 等通用函式操作。
://
scheme: 封裝協定名稱(php, file, http, ftp, zip, compress.zlib, phar...)
target: 由該封裝協定語法定義的目標資源
print_r(stream_get_wrappers());
/* 輸出範例:
Array
(
[0] => php
[1] => file
[2] => glob
[3] => data
[4] => http
[5] => ftp
[6] => zip
[7] => compress.zlib
[8] => https
[9] => ftps
[10] => phar
)
*/
// 本地檔案(file:// 為預設)
$local = file_get_contents('/home/bar/foo.txt');
$local = file_get_contents('file:///home/bar/foo.txt'); // 等效
// HTTP/HTTPS
$http = file_get_contents('https://www.example.com/foo.txt');
$https = file_get_contents('https://www.example.com/foo.txt');
// FTP/FTPS
$ftp = file_get_contents('ftp://user:pass@ftp.example.com/foo.txt');
$ftps = file_get_contents('ftps://user:pass@ftp.example.com/foo.txt');
| 流 | 用途 |
|---|---|
php://stdin | CLI 標準輸入 |
php://stdout | 標準輸出 |
php://stderr | 標準錯誤 |
php://input | POST 原始請求體(唯讀) |
php://output | 輸出緩衝區(唯寫) |
php://fd/N | 檔案描述符 N |
php://memory | 純記憶體暫存流 |
php://temp | 超過 2MB 自動落地暫存檔 |
php://filter | 資料流過濾器元封裝 |
$opts = [
'http' => [
'method' => 'GET',
'timeout' => 60,
]
];
$context = stream_context_create($opts);
$html = file_get_contents('https://www.example.com', false, $context);
print_r(stream_get_filters());
/* 輸出範例:
Array
(
[0] => convert.iconv.*
[1] => mcrypt.*
[2] => mdecrypt.*
[3] => string.rot13
[4] => string.toupper
[5] => string.tolower
[6] => string.strip_tags
[7] => convert.*
[8] => consumed
[9] => dechunk
[10] => zlib.*
)
*/
class StrtoupperFilter extends php_user_filter {
public function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = strtoupper($bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
stream_filter_register("strtoupper", "StrtoupperFilter") or die("註冊失敗");
$fp = fopen("foo-bar.txt", "w");
stream_filter_append($fp, "strtoupper");
fwrite($fp, "Line1\nWord - 2\nEasy As 123\n");
fclose($fp);
readfile("foo-bar.txt");
/* 結果:
LINE1
WORD - 2
EASY AS 123
*/
使用 stream_wrapper_register() 實作 streamWrapper 介面,可建立自定義協定(如 s3://、db://)。