Stream (流) 是 PHP 統一**文件、網絡、壓縮、進程間通訊**等「可讀寫、可定位」資源的抽象層。自 PHP 4.3 引入,**幾乎所有 I/O 操作 (fopen, file_get_contents, copy, stream_copy_to_stream) 底層均走 Stream API**。
://
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/https | HTTP 客戶端 | file_get_contents('https://api...')、stream_context_create 定制請求 |
| ftp/ftps | FTP 客戶端 | 遠程文件讀寫 |
| compress.zlib / compress.bzip2 | 壓縮流 | gzopen() 別名、copy('compress.zlib://file.gz', 'out.txt') |
| php | PHP 內部 I/O | php://input (原始 POST)、php://stdin/out/err、php://memory、php://temp、php://filter |
| data | 內聯數據 | data:text/plain,hello、data://text/plain;base64,... |
| glob | 文件模式匹配 | glob://*.php 遍歷 |
| phar | PHAR 歸檔 | 打包發布、require 'phar://app.phar/vendor/autoload.php' |
| zip | ZIP 歸檔 | zip://archive.zip#file.txt 直接讀取壓縮包內文件 |
| ssh2 | SSH2 SFTP | ssh2.sftp://user:pass@host/path (需 ssh2 擴展) |
$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);
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'));
// 寫入時 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.*
$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
實現 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');
s3://、gcs:// 使代碼無感遷移。encrypt:// 包裝器自動加解密,業務代碼按普通文件操作。syslog://、kafka:// 直接 fwrite。test:// 模擬網絡/文件行為。Stream 是 PHP I/O 的**統一抽象層**。掌握內建包裝器、Context 定制、Filter 鏈式處理、自定義 Wrapper 註冊,能讓你用統一的 fopen/fread/fwrite/fclose API 操作本地文件、HTTP API、壓縮包、加密存儲、雲對象存儲,**業務代碼零修改遷移底層存儲**,極大提升可維護性與可測試性。