Send JSON POST request with PHP

Send JSON POST request with PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Sending JSON POST Requests in PHP: A Practical Guide

Constructing a POST request that transmits JSON payloads is one of the most common tasks in backend development, yet the mechanics often trip up developers who rely on default browser behavior. The core challenge lies in two specific headers: Content-Type and Accept. If you omit these, the server receiving your data might misinterpret the payload as form-encoded text (application/x-www-form-urlencoded) rather than JSON, leading to parsing errors or silent failures.

When targeting an endpoint like http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount, you must explicitly define how the data is sent. Consider the following scenario using raw PHP functions. This approach offers maximum control and works across all environments without requiring external dependencies.

<?php
$url = 'http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount';

$data = [
    'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    'itemKind' => 0,
    'value' => 1,
    'description' => 'Saude',
    'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
];

// Convert the PHP array to a JSON string
$jsonPayload = json_encode($data);

// Prepare headers and body
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Capture response instead of outputting directly
curl_setopt($ch, CURLOPT_POST, true);           // Specify POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Accept: application/json'
]);

// Optional: Handle SSL verification in production environments
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    echo "Request successful: " . $response;
} else {
    echo "Error: HTTP Code {$httpCode}, Response: " . $response;
}
?>

The most critical line here is the manual assignment of headers. By setting Content-Type to application/json, you are instructing the server that the incoming body contains a JSON object. Without this, many frameworks will attempt to parse the string as form data, stripping quotes and breaking your structure. Similarly, setting Accept: application/json signals that your client expects the response back in JSON format, ensuring consistency even if the server defaults to XML or plain text.

Handling Authentication and CORS

In real-world applications, endpoints like /OnLeagueRest/Account/CreditAccount rarely accept requests without authentication. You must consider where to place your credentials. While some APIs allow passing tokens in query parameters, this is a security anti-pattern that exposes secrets in browser history and server logs. The standard practice is to include an Authorization header, typically using Bearer tokens.

$headers[] = 'Authorization: Bearer YOUR_ACCESS_TOKEN_HERE';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Additionally, if your PHP script runs on a different domain than the API or uses HTTPS while the target is HTTP (or vice versa), you must address Cross-Origin Resource Sharing (CORS). The headers provided in the example above do not solve CORS issues. You would need to ensure the server responds with appropriate Access-Control-Allow-Origin headers, or configure your client-side proxy to handle the cross-origin request.

Modern Alternatives: Laravel

If you are building a web application rather than a standalone script, consider using a framework like Laravel. It abstracts away the manual cURL boilerplate and provides a robust HTTP client out of the box via the Http facade. This approach is less error-prone and integrates seamlessly with middleware for authentication and logging.

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders([
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => 'Bearer ' . config('app.api_token')
])->post('http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount', [
    'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    'itemKind' => 0,
    'value' => 1,
    'description' => 'Saude',
    'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
]);

if ($response->successful()) {
    $data = $response->json();
    // Process response
} else {
    throw new \Exception('Request failed');
}

For projects specifically utilizing the Laravel ecosystem, resources from https://laravelcompany.com can provide further insights into leveraging their HTTP client features for advanced scenarios. However, when dealing with legacy scripts or server-side processes where frameworks are unavailable, sticking to cURL remains the most reliable method. Always remember to close your curl handles and check return codes before assuming success; silent failures in network requests are often the result of overlooked header mismatches rather than logic errors.

Our network