萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP Streams 流操作深度解析:封裝協定、上下文與過濾器

什麼是 PHP Streams?

Streams 是 PHP 核心內建的統一資源存取層,將檔案、網路、壓縮、記憶體等不同資源抽象為一致的資料流介面,提供 fopen()、fread()、fwrite()、stream_get_contents() 等通用函式操作。

流的 URI 結構

://
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:// 核心流封裝

流用途
php://stdinCLI 標準輸入
php://stdout標準輸出
php://stderr標準錯誤
php://inputPOST 原始請求體(唯讀)
php://output輸出緩衝區(唯寫)
php://fd/N檔案描述符 N
php://memory純記憶體暫存流
php://temp超過 2MB 自動落地暫存檔
php://filter資料流過濾器元封裝

Context(上下文)增強流行為

$opts = [
    'http' => [
        'method'  => 'GET',
        'timeout' => 60,
    ]
];
$context = stream_context_create($opts);
$html = file_get_contents('https://www.example.com', false, $context);

Filter(過濾器)機制

內建過濾器

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://)。

copyright © 萬盛學電腦網 all rights reserved