How to POST JSON Data With PHP cURL?
When attempting to send a raw JSON payload via cURL to a REST API, the most common pitfall occurs in how the data is wrapped before transmission. In the scenario provided, the developer attempts to mimic a Shopify-style API request by encoding an array into a string and then nesting that string inside another associative array key named customer.
The output of an empty $_POST array on the receiving end confirms the issue: PHP's default superglobals expect form-encoded data (e.g., key=value&other=thing) or multipart forms. When you pass raw JSON, even if the headers claim it is JSON, standard PHP scripts that rely on $_POST will not parse it automatically. Furthermore, the specific code snippet wraps the JSON string inside an additional layer: array("customer"=>$data_string). This results in a payload structure like {"customer": "{\"first_name\": \"...\"}"}. Most APIs expect the JSON root object to match their schema directly, not wrapped inside a generic key unless the API documentation explicitly demands it.
The Core Problem: Payload Structure and Headers
The primary failure point lies in the CURLOPT_POSTFIELDS configuration. The provided code constructs a payload where the actual data is nested one level deep. If the target API expects the root object to contain keys like first_name, last_name, and email, sending them inside a customer key causes the parser on the receiving end to ignore them or fail validation.
Additionally, while the code sets 'Content-Type: application/json', it also manually calculates and sets 'Content-Length'. Modern HTTP clients and servers, including PHP's cURL extension, automatically handle the Content-Length header based on the size of the actual data sent. Manually overriding this can sometimes lead to inconsistencies if the string encoding changes or if the server recalculates the length differently.
To fix the empty $_POST array issue, you must ensure two things:
- The JSON structure matches exactly what the API expects (no unnecessary nesting).
- You are aware that
$_POSTwill remain empty when receiving raw JSON and that you must parse the response or input stream manually usingfile_get_contents('php://input').
Correcting the cURL Implementation
To send data correctly, strip the intermediate array wrapper and pass the encoded JSON string directly. Here is the corrected approach:
$url = 'https://api.example.com/customers'; // Replace with actual endpoint
$data = [
"first_name" => "First name",
"last_name" => "Last name",
"email" => "email@gmail.com",
"addresses" => [
"address1" => "some address",
"city" => "city",
"country" => "CA",
"province" => "ON",
"zip" => "123 ABC"
]
];
// Convert the PHP array directly to a JSON string
$data_string = json_encode($data, JSON_UNESCAPED_UNICODE);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); // Send directly, no wrapper
curl_setopt($ch, CURLOPT_HEADER, false); // Typically hide headers in output unless debugging
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Capture response to variable
// Set headers only if Content-Length needs manual control (usually not required)
$headers = [
'Content-Type: application/json'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Check for errors
if ($result === false) {
echo "cURL Error: " . curl_error($ch);
} else {
echo "HTTP Code: $httpCode\n";
echo "Response: $result";
}
Handling the Response on the Server Side
The original example showed retrieving data via print_r($_POST) and receiving an empty array. This is expected behavior for any server receiving raw JSON. PHP does not automatically populate $_POST with JSON content.
To access the sent data in PHP, you must read the raw input stream using php://input. You should never rely on $_POST or $_GET for APIs that communicate via JSON. Instead, decode the raw input string into an associative array:
$rawInput = file_get_contents('php://input');
$inputData = json_decode($rawInput, true);
if (json_last_error() === JSON_ERROR_NONE) {
// Access data correctly
$firstName = $inputData['first_name'];
$addresses = $inputData['addresses'];
} else {
// Handle invalid JSON
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON payload']);
exit;
}
This pattern ensures that your REST endpoint correctly interprets the incoming request regardless of whether it is a POST or PUT operation. If you are building a larger application, consider using a framework like Laravel, which abstracts these low-level details and provides robust input validation out of the box. For more detailed guidance on handling API requests in PHP environments, resources such as LaravelCompany offer comprehensive documentation on modernizing legacy cURL scripts into maintainable RESTful services.
Summary of Best Practices
- Avoid unnecessary nesting: Do not wrap JSON strings inside another array unless the API specification explicitly requires a wrapper object (e.g.,
{"data": {...}}). - Remove manual Content-Length: Let cURL calculate this automatically to prevent length mismatches.
- Use
php://input: Always read raw JSON from the input stream, not$_POST. - Validate JSON errors: Check
json_last_error()before accessing decoded data to prevent undefined index notices.
