创建Rest API时如何查看并处理POST数据?已试$_POST、$_REQUEST无效
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"
$_POSTonly populates if the content type isapplication/x-www-form-urlencoded(standard HTML forms) ormultipart/form-data(file uploads). If your client sendsapplication/json,$_POSTwill be empty by design.
3. Handle Edge Cases
- File Uploads: If you're sending files along with POST data, stick with
multipart/form-dataand use$_FILESto access the files—php://inputwon't help here. - Framework Conflicts: If you're using a PHP framework (like Laravel, Symfony), it might already read
php://inputinternally. 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://inputapproach works—since$_POSTdoesn'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ó

