Reading JSON POST using PHP
When your web service switches from accepting standard form-encoded data to handling raw JSON payloads, the underlying mechanism for retrieving input changes completely. If you are sending a Content-Type: application/json header and still finding that your $_POST array is empty or causing errors, the issue lies in how PHP parses the request body based on the application/x-www-form-urlencoded or multipart/form-data defaults.
The core problem is that PHP automatically populates the $_POST superglobal only when it detects form data formats. When a client sends raw JSON with application/json, PHP ignores the body for $_POST. Consequently, attempting to access $_POST['action'] in your script will yield an empty array or null, leading to logic failures or silent errors depending on how you check the condition.
To resolve this, you must read the raw input stream directly. The standard approach is to use file_get_contents('php://input'). This function reads the body of the request exactly as it was sent by the client, bypassing PHP's automatic parsing logic. Once you have the raw string, you need to decode it into a usable data structure using json_decode().
Here is how the server-side logic should be structured to handle this correctly:
<?php
// Set the response header immediately
header('Content-type: application/json');
// Read the raw request body
$inputJSON = file_get_contents('php://input');
// Check if input exists to avoid warnings on empty requests
if ($inputJSON === '') {
echo json_encode(['error' => 'No input data provided']);
exit;
}
// Decode the JSON string into an associative array
$input = json_decode($inputJSON, true);
// Now you can safely access the data like an array
$action = $input['action'] ?? null;
if ($action === 'login') {
// Simulate database logic here
$statusCode = ['statusCode' => 1, 'statusDescription' => 'Login Process - Fail'];
// Send the response back as JSON
echo json_encode([
'data' => [
'status' => $statusCode
]
]);
} else {
echo json_encode(['error' => 'Invalid action']);
}
// Close database connection if needed
// mysql_close($link);
?>
On the client side, ensuring the data is serialized correctly before sending is equally important. Your cURL configuration needs to ensure that $data is converted into a JSON string using json_encode() before being assigned to CURLOPT_POSTFIELDS. Additionally, you must explicitly set the Content-Type: application/json header so the server knows how to interpret the payload.
$data = [
'action' => 'login',
'username' => 'user',
'password' => 'pass'
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Encode data first
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($data))
]);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');
$result = curl_exec($curl);
curl_close($curl);
Why $_POST Fails with JSON
It is a common misconception that $_POST captures all incoming data. In reality, PHP distinguishes between different media types during the HTTP request parsing phase. When you send application/json, the web server passes the body to PHP as raw text. PHP's internal parser then looks for specific markers like = or & (for URL encoding) or form boundaries to populate $_POST. Since JSON lacks these markers, $_POST remains empty.
Using file_get_contents('php://input') is the modern standard for handling raw payloads in PHP 5.6 and later. It works seamlessly with both JSON and XML streams. However, there are trade-offs to consider. If your application needs to support legacy clients sending form data (application/x-www-form-urlencoded) alongside new JSON clients, you must implement a detection strategy. You can check the Content-Type header or verify if $_POST is populated before deciding whether to read from the raw input stream or the superglobal.
Another critical consideration is error handling. If the client sends malformed JSON, json_decode() will return null. Always verify the result of json_decode() and check if $inputJSON is empty before accessing array keys. Accessing an undefined index in a decoded array can lead to "Undefined array key" warnings or unexpected behavior depending on your PHP error reporting settings.
For modern PHP applications, especially those built with frameworks like Laravel, handling JSON input is often abstracted away. Frameworks typically provide specific methods to access request data regardless of the content type, but understanding the raw mechanics remains essential for debugging and when writing custom middleware or legacy scripts. If you are integrating this into a larger ecosystem, platforms like https://laravelcompany.com offer robust examples of handling JSON payloads within modern PHP frameworks, demonstrating how to maintain backward compatibility while adopting new input standards.
By switching to php://input and ensuring proper serialization on the client, you align your service with current HTTP standards. This approach ensures that your web service can reliably process complex data structures without relying on deprecated or format-specific superglobals.
