萬盛學電腦網

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

PHP 輸入輸出流(php://)完整操作指南

php:// 封裝協定簡介

PHP 透過 php:// 封裝協定存取標準輸入/輸出、請求原始資料、記憶體/暫存檔流、過濾器等,提供統一的資料流介面。

常用流封裝

封裝協定說明
php://stdin標準輸入(唯讀),CLI 腳本讀取鍵盤輸入
php://stdout標準輸出(唯寫)
php://stderr標準錯誤輸出(唯寫)
php://input請求原始資料(唯讀),POST 請求替代 $HTTP_RAW_POST_DATA,不依賴 php.ini、記憶體較省
php://output輸出緩衝區(唯寫),類似 echo/print
php://fd/N直接存取檔案描述符 N
php://memory記憶體暫存流,資料常駐記憶體
php://temp暫存流,超過 2MB(預設)自動轉寫入臨時檔案
php://filter元封裝器,資料流開啟時套用過濾器

實戰範例

讀取 POST 原始資料

<form action="" method="post">
<input type="text" name="test">
<input type="submit">
</form>
<?php
echo file_get_contents("php://input");
?>
php://input 示例輸出

使用過濾器轉換大小寫

<?php
// 以大寫輸出遠端網頁內容
readfile("php://filter/read=string.toupper/resource=https://www.example.com");
?>

php://filter 參數說明

php://filter 參數圖解

進階:自訂過濾器

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\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");
fclose($fp);

readfile("foo-bar.txt");
/* 輸出:
LINE1
WORD - 2
EASY AS 123
*/
copyright © 萬盛學電腦網 all rights reserved