萬盛學電腦網

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

PHP I/O 流深度解析:php:// 輸入輸出流、過濾器與臨時流完整指南

概覽

PHP 提供 php:// 協議族,統一訪問標準輸入/輸出/錯誤、請求原始體、輸出緩衝、文件描述符、內存/臨時文件流及流過濾器。掌握這些流對構建高性能 API、CLI 工具、流式處理大數據至關重要。

標準流:stdin / stdout / stderr

<?php
// 讀取標準輸入(CLI 模式下管道輸入、POST 原始體)
$stdin = fopen('php://stdin', 'r');
$input = stream_get_contents($stdin);
fclose($stdin);

// 寫入標準輸出(正常輸出)
$stdout = fopen('php://stdout', 'w');
fwrite($stdout, "正常輸出\n");
fclose($stdout);

// 寫入標準錯誤(錯誤/日誌輸出,可單獨重定向)
$stderr = fopen('php://stderr', 'w');
fwrite($stderr, "錯誤信息\n");
fclose($stderr);
?>

CLI 實戰:cat data.json | php process.php 中 php://stdin 讀取管道數據;php script.php > out.log 2> err.log 分離正常/錯誤輸出。

請求原始體:php://input

唯一可靠讀取非表單 POST 數據的方式(JSON、XML、Protobuf 等)。優於 $HTTP_RAW_POST_DATA(已棄用/移除):不依賴 always_populate_raw_post_data 設置,內存佔用更低(流式讀取)。

<?php
// Content-Type: application/json
$raw = file_get_contents('php://input'); // 獲取完整 JSON 字符串
$data = json_decode($raw, true);

// 流式讀取大請求體(避免一次性載入內存)
$stream = fopen('php://input', 'r');
while (!feof($stream)) {
    $chunk = fread($stream, 8192);
    // 流式處理...
}
fclose($stream);
?>

限制:multipart/form-data 請求不可用(PHP 已解析填充 $_FILES/$_POST)。

輸出緩衝流:php://output

只寫流,直接寫入 PHP 輸出緩衝區,等價於 echo/print 但可作為流操作:

<?php
$fp = fopen('php://output', 'w');
fwrite($fp, "Hello ");
fwrite($fp, "World\n");
fclose($fp);

// 實戰:流式導出大 CSV,避免內存爆炸
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
$out = fopen('php://output', 'w');
fputcsv($out, ['ID', 'Name', 'Email']);
foreach ($hugeDataset as $row) {
    fputcsv($out, $row); // 逐行輸出,無需載入全量數據
}
fclose($out);
?>

文件描述符直接訪問:php://fd/N

直接操作進程文件描述符(FD),高級系統編程場景:

<?php
// FD 3 為自定義管道/套接字
$fd3 = fopen('php://fd/3', 'r+');
stream_socket_sendto($fd3, "data");
$resp = fread($fd3, 1024);
fclose($fd3);
?>

內存與臨時流:php://memory vs php://temp

特性php://memoryphp://temp
存儲介質純內存內存 → 臨時文件(超閾值)
預設閾值無(永不落盤)2 MB(可配置)
適用場景小數據、極高速需求不確定大小、防止 OOM
臨時文件位置—sys_get_temp_dir()
<?php
// 自定義閾值 1MB
$temp = fopen('php://temp/maxmemory:1048576', 'r+');
fwrite($temp, str_repeat('x', 2 * 1024 * 1024)); // 2MB 將落盤
rewind($temp);
echo ftell($temp); // 2097152
fclose($temp);
?>

流過濾器:php://filter 元封裝器

在流打開時掛載過濾器,**對 readfile()、file()、file_get_contents() 等「一體式」函數極其關鍵**,因為這些函數不提供 stream_filter_append() 機會。

語法結構

php://filter/=/resource=

內建過濾器示例

<?php
// 1. 大寫轉換讀取遠程頁面
readfile('php://filter/read=string.toupper/resource=https://example.com');

// 2. Base64 解碼讀取
$decoded = file_get_contents('php://filter/read=convert.base64-decode/resource=data://text/plain;base64,SGVsbG8=');

// 3. 寫入時自動 ROT13 加密
$fp = fopen('php://filter/write=string.rot13/resource=php://memory', 'w');
fwrite($fp, 'Secret');
rewind($fp);
echo stream_get_contents($fp); // Frperg
fclose($fp);

// 4. 鏈式過濾:先去標籤再大寫
$clean = file_get_contents('php://filter/read=string.strip_tags|string.toupper/resource=php://input');
?>

常用內建過濾器

  • string.*:toupper、tolower、rot13、strip_tags
  • convert.*:base64-encode/decode、quoted-printable-encode/decode、iconv.*(編碼轉換)
  • zlib.*:deflate、inflate(壓縮/解壓)
  • mcrypt.*、openssl.*:加密/解密(需對應擴展)

data:// 協議補充

雖非 php://,但常配合過濾器使用:

<?php
// 直接將字符串作為流讀取
$data = file_get_contents('data://text/plain;base64,' . base64_encode('Hello World'));
// 等價於
$data = file_get_contents('php://filter/read=convert.base64-decode/resource=data://text/plain;base64,' . base64_encode('Hello World'));
?>

總結與最佳實踐

  1. API 開發:統一使用 php://input 讀取原始請求體,支援 JSON/Protobuf/MessagePack。
  2. 大數據導出:php://output + fputcsv 流式寫入,恆定內存佔用。
  3. 大數據導入:php://temp 緩衝上傳文件,超閾值自動落盤,安全不爆內存。
  4. 流式轉換:php://filter 鏈式處理編碼、壓縮、加密,無需中間文件。
  5. CLI 工具:php://stdin/stdout/stderr 構建 Unix 哲學管道工具。

善用 PHP 流抽象層,能將「文件/網絡/內存/進程」統一為可組合、可管道化的流操作,是編寫高性能、低內存、可測試代碼的關鍵技能。

copyright © 萬盛學電腦網 all rights reserved