You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建Rest API时如何查看并处理POST数据?已试$_POST、$_REQUEST无效

Troubleshooting POST Data Access in Your PHP REST API

Hey there! I totally get the frustration when $_POST and $_REQUEST don't pick up your POST data—this usually boils down to the content type your client is sending, since those superglobals only work with specific formats. Let's break down the alternative methods you can use:

1. Read Raw POST Data with php://input

This is the go-to solution for REST APIs that send JSON, XML, or any non-form-encoded data. php://input is a read-only stream that gives you the entire raw HTTP request body, regardless of the content type.

For JSON payloads (the most common case in REST APIs), here's how to parse it:

// Get the raw POST data
$rawRequestBody = file_get_contents('php://input');

// Decode it into an associative array (use false for an object)
$postData = json_decode($rawRequestBody, true);

// Now you can access your data like any array
if ($postData) {
    $username = $postData['username'];
    $email = $postData['email'];
}

2. Verify the Request's Content-Type

First, check what content type your client is sending—this will tell you why $_POST isn't working. You can get this from the $_SERVER superglobal:

echo $_SERVER['CONTENT_TYPE']; // e.g., "application/json" or "text/plain"
  • $_POST only populates if the content type is application/x-www-form-urlencoded (standard HTML forms) or multipart/form-data (file uploads). If your client sends application/json, $_POST will be empty by design.

3. Handle Edge Cases

  • File Uploads: If you're sending files along with POST data, stick with multipart/form-data and use $_FILES to access the files—php://input won't help here.
  • Framework Conflicts: If you're using a PHP framework (like Laravel, Symfony), it might already read php://input internally. In that case, use the framework's built-in request methods (e.g., $request->json() in Laravel) instead of reading the stream directly.
  • PUT/PATCH Requests: If you ever need to handle these methods later, the same php://input approach works—since $_POST doesn't populate for non-POST methods either.

Quick Debug Tip

If you're unsure what's being sent, dump the raw request body to see exactly what your client is sending:

var_dump(file_get_contents('php://input'));

That should cover all the bases! Let me know if you run into any specific issues with parsing or content types.

内容的提问来源于stack exchange,提问作者Árpád Jó

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:08:55