萬盛學電腦網

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

深入理解 PHP Streams:從基礎包裝器到自定義 Stream 實戰

什麼是 Stream?

Stream (流) 是 PHP 統一**文件、網絡、壓縮、進程間通訊**等「可讀寫、可定位」資源的抽象層。自 PHP 4.3 引入,**幾乎所有 I/O 操作 (fopen, file_get_contents, copy, stream_copy_to_stream) 底層均走 Stream API**。

Stream URI 結構

://
scheme: 包裝器協議 (file, http, ftp, compress.zlib, php, data, glob, phar, zip, ssh2...)
target: 包裝器特定路徑/參數

示例:file:///etc/passwd、https://example.com/api、compress.zlib://data.txt.gz、php://input、phar://app.phar/vendor/autoload.php。

內建包裝器速查

Scheme用途典型場景
file本地文件系統默認包裝器,fopen('/path') 等同 fopen('file:///path')
http/httpsHTTP 客戶端file_get_contents('https://api...')、stream_context_create 定制請求
ftp/ftpsFTP 客戶端遠程文件讀寫
compress.zlib / compress.bzip2壓縮流gzopen() 別名、copy('compress.zlib://file.gz', 'out.txt')
phpPHP 內部 I/Ophp://input (原始 POST)、php://stdin/out/err、php://memory、php://temp、php://filter
data內聯數據data:text/plain,hello、data://text/plain;base64,...
glob文件模式匹配glob://*.php 遍歷
pharPHAR 歸檔打包發布、require 'phar://app.phar/vendor/autoload.php'
zipZIP 歸檔zip://archive.zip#file.txt 直接讀取壓縮包內文件
ssh2SSH2 SFTPssh2.sftp://user:pass@host/path (需 ssh2 擴展)

php:// 系列深度解析

1. php://input — 讀取原始 POST Body

$raw = file_get_contents('php://input'); // 僅支持 application/x-www-form-urlencoded, multipart/form-data 以外的內容
// JSON API 典型用法
$data = json_decode(file_get_contents('php://input'), true);

2. php://memory / php://temp — 內存/臨時文件流

  • php://memory:純內存,適合小數據 (< 2MB)。
  • php://temp:閾值 (默認 2MB) 以下內存,超過自動落盤到系統臨時目錄。
$fp = fopen('php://temp', 'r+');
fwrite($fp, $largeData);
rewind($fp);
// 當作普通文件句柄傳遞給其他函數
stream_copy_to_stream($fp, fopen('output.dat', 'w'));

3. php://filter — 元包裝器,鏈式過濾

// 寫入時 ROT13 編碼
file_put_contents('php://filter/write=string.rot13/resource=file:///tmp/secret.txt', 'Hello');

// 讀取時大寫 + ROT13 解碼
echo file_get_contents('php://filter/read=string.toupper|string.rot13/resource=https://example.com/');

// 內建過濾器
// string.rot13, string.toupper, string.tolower, string.strip_tags
// convert.iconv.ISO-8859-1/UTF-8, convert.base64-encode/decode
// zlib.*, bzip2.*, mcrypt.*, mdecrypt.*

Stream Context (上下文) —— 修改包裝器行為

$opts = [
    'http' => [
        'method'  => 'POST',
        'header'  => "Authorization: Bearer $token\r\nContent-Type: application/json\r\n",
        'content' => json_encode(['key' => 'value']),
        'timeout' => 10,
        'follow_location' => 1,
        'max_redirects' => 5,
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
        'cafile' => '/etc/ssl/certs/ca-certificates.crt',
    ],
];
$ctx = stream_context_create($opts);
$response = file_get_contents('https://api.example.com/endpoint', false, $ctx);
// 等同於 cURL 但純 PHP 流式 API

自定義 Stream Wrapper 實戰

實現 s3://bucket/key 直接讀寫 AWS S3 (簡化版):

class S3StreamWrapper {
    public $context;
    private $bucket, $key, $position = 0;
    private $client; // Aws\S3\S3Client

    public function stream_open($path, $mode, $options, &$opened_path) {
        // 解析 s3://bucket/key
        $parsed = parse_url($path);
        $this->bucket = $parsed['host'];
        $this->key = ltrim($parsed['path'], '/');
        $this->client = new Aws\S3\S3Client(['region' => 'us-east-1']);
        $this->position = 0;
        return true;
    }

    public function stream_read($count) {
        $result = $this->client->getObject([
            'Bucket' => $this->bucket,
            'Key'    => $this->key,
            'Range'  => "bytes={$this->position}-" . ($this->position + $count - 1),
        ]);
        $data = (string)$result['Body'];
        $this->position += strlen($data);
        return $data;
    }

    public function stream_write($data) {
        // 簡化:追寫不支援,實際需分片上傳
        return false;
    }

    public function stream_tell() { return $this->position; }
    public function stream_eof() { return $this->position >= $this->getSize(); }
    public function stream_seek($offset, $whence = SEEK_SET) { /* ... */ return true; }
    public function stream_stat() { return ['size' => $this->getSize()]; }
    public function url_stat($path, $flags) { return $this->stream_stat(); }

    private function getSize() {
        $obj = $this->client->headObject(['Bucket' => $this->bucket, 'Key' => $this->key]);
        return $obj['ContentLength'];
    }
}
// 註冊
stream_wrapper_register('s3', S3StreamWrapper::class) or die('註冊失敗');

// 使用
$content = file_get_contents('s3://my-bucket/path/to/file.txt');
copy('local.pdf', 's3://my-bucket/backups/local.pdf');

實際應用場景

  1. 虛擬文件系統:PaaS (Heroku, AppFog) 無持久磁盤,掛載 s3://、gcs:// 使代碼無感遷移。
  2. 加密文件透明讀寫:encrypt:// 包裝器自動加解密,業務代碼按普通文件操作。
  3. 日誌聚合:syslog://、kafka:// 直接 fwrite。
  4. 測試雙:單元測試中註冊 test:// 模擬網絡/文件行為。

結語

Stream 是 PHP I/O 的**統一抽象層**。掌握內建包裝器、Context 定制、Filter 鏈式處理、自定義 Wrapper 註冊,能讓你用統一的 fopen/fread/fwrite/fclose API 操作本地文件、HTTP API、壓縮包、加密存儲、雲對象存儲,**業務代碼零修改遷移底層存儲**,極大提升可維護性與可測試性。

copyright © 萬盛學電腦網 all rights reserved