`php://filter` 是 PHP 中的一種偽協議,它允許開發者在數據讀取或寫入過程中應用過濾器,從而實現對數據的處理。以下是 `php://filter` 偽協議的詳細介紹:
基本概念
`php://filter` 是 PHP 獨有的一種協議,它是一種過濾器,可以作為一個中間流來過濾其他的數據流。通常使用該協議來讀取或者寫入部分數據,并在讀取和寫入之前對數據進行一些過濾,例如 base64 編碼處理、rot13 處理等。
使用方法
`php://filter` 的一般使用方法為:
php://filter/過濾器|過濾器/resource=要過濾的數據流
過濾器可以設置多個,使用管道符 `|` 分隔,按照從左到右的方式依次使用相應的過濾器進行過濾處理。例如:
echo file_get_contents("php://filter/read=convert.base64-encode|convert.base64-encode/resource=data://text/plain,
上述代碼對 `
過濾器分類
根據 PHP 官方文檔,`php://filter` 協議的過濾器大致可以分為以下四類:
1. **字符串過濾器**:例如 `string.rot13`、`string.toupper`、`string.tolower`、`string.strip_tags`。
2. **轉換過濾器**:例如 `convert.base64-encode`、`convert.base64-decode`、`convert.quoted-printable-encode`、`convert.quoted-printable-decode`。
3. **壓縮過濾器**:例如 `zlib.deflate`(壓縮)、`zlib.inflate`(解壓)、`bzip2.compress`(壓縮)、`bzip2.decompress`(解壓)。
4. **加密過濾器**:例如 `mcrypt.*`、`mdecrypt.*`(這些特性自 PHP 7.1.0 起已廢棄)。
示例代碼
以下是一個簡單的示例代碼,展示如何使用 `php://filter` 進行 base64 編碼:
echo file_get_contents("php://filter/read=convert.base64-encode/resource=data://text/plain,Hello World!");
// 輸出:SGVsbG8gV29ybGQh
注意事項
- `php://filter` 偽協議可以用于 `include()`、`file()`、`file_get_contents()`、`readfile()`、`file_put_contents()` 等函數。
- 在使用 `php://filter` 偽協議時,確保過濾器和資源路徑正確無誤,否則可能會導致錯誤。