首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 輸入流 php://input 讀取原始 POST 數據

     編輯:PHP 相關知識

php://input 是 PHP 提供的只讀流,用於讀取請求體原始數據。適用於 Content-Type: application/json、application/xml、application/octet-stream 等非表單編碼場景,是 API 接口、文件上傳、Webhook 處理的核心機制。

適用條件

  • 請求方法:POST、PUT、PATCH
  • Content-Type ≠ multipart/form-data
  • Content-Type ≠ application/x-www-form-urlencoded (此類自動填充 $_POST)

基礎用法

<?php
// 獲取原始請求體
$raw = file_get_contents('php://input');

// JSON API 典型處理
$data = json_decode($raw, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    exit('Invalid JSON');
}

// 處理業務邏輯...
echo json_encode(['status' => 'ok', 'received' => $data]);

對比:$_POST vs php://input vs $HTTP_RAW_POST_DATA

特性$_POSTphp://input$HTTP_RAW_POST_DATA
數據來源表單解析結果原始請求體原始請求體
Content-Type 支持form-urlencoded, multipart所有非 multipart所有非 multipart
內存佔用解析後結構流式讀取可控總是全量載入
配置需求無無需 always_populate_raw_post_data=On (PHP 5.6 棄用, 7.0 移除)
多次讀取可重複訪問單次流 (需手動存儲)可重複訪問

進階場景

1. 大文件流式處理 (避免內存溢出)

<?php
$input = fopen('php://input', 'r');
$output = fopen('/uploads/large_file.bin', 'w');

while (!feof($input)) {
    $chunk = fread($input, 8192);
    if ($chunk === '') break;
    fwrite($output, $chunk);
}

fclose($input);
fclose($output);
// 內存佔用恆定 ~8KB,不受文件大小影響

2. 多部分解析 (手動處理 multipart)

<?php
// 非標準 multipart 或需流式解析時
$raw = file_get_contents('php://input');
// 使用 pecl_http 的 HttpMessage 或手動按 boundary 分割解析
// 一般建議直接用 $_FILES/$_POST

3. Webhook 驗證簽名 (GitHub/Stripe/微信支付)

<?php
$raw = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? ''; // GitHub
$secret = 'webhook_secret';

$expected = 'sha256=' . hash_hmac('sha256', $raw, $secret);
if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    exit('Invalid signature');
}

$payload = json_decode($raw, true);
// 處理事件...

4. XML/SOAP 接口

$xml = file_get_contents('php://input');
$dom = new DOMDocument();
$dom->loadXML($xml);
// XPath 查詢處理...

常見坑點

  1. 已讀取無法再讀:流讀取後指針在末尾,需 $raw = file_get_contents(...) 存儲變量複用
  2. multipart/form-data 不可用:上傳文件時用 $_FILES
  3. Nginx proxy_buffering:大請求體可能被緩衝到磁盤,導致 php://input 讀取為空,需設置 proxy_request_buffering off;
  4. PHP 內置服務器:php -S 完整支持 php://input

現代框架封裝

  • Laravel:$request->getContent() / $request->json()
  • Symfony:$request->getContent()
  • Slim/Lumen:$request->getBody() (PSR-7 StreamInterface)

掌握 php://input 是構建現代 PHP API、Webhook、文件服務的基石。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved