Reading Raw Request Body
Current Request
| Property | Value |
|---|---|
| Request Method | GET |
| Content-Type | (none) |
| Content-Length | (none) |
No request body received. This page is loaded via GET.
Use curl to send POST data - see examples below.
Test with curl
Copy and paste these commands in your terminal:
Send JSON Data
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"alice@example.com","age":25}' \
https://cse135.site/php-tutorial/03-headers/raw-body.php
Get JSON Response
curl -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"message":"Hello from curl!"}' \
https://cse135.site/php-tutorial/03-headers/raw-body.php
The PHP Code
<?php
// Read raw request body
$rawBody = file_get_contents('php://input');
// Check Content-Type
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos($contentType, 'application/json') !== false) {
// Parse JSON
$data = json_decode($rawBody, true);
// Check for errors
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => json_last_error_msg()]);
exit;
}
// Use $data as PHP array
echo "Hello, " . htmlspecialchars($data['name']);
}
?>
Why php://input?
$_POST only works for:
application/x-www-form-urlencoded(HTML form default)multipart/form-data(file uploads)
For JSON, XML, or other content types, use php://input.
Previous: Content Negotiation | Back to Module | Next: Sessions