PHP Code Examples

Send JSON Data with PHP cURL

Send a JSON payload to an API using cURL and inspect the HTTP response.

Example

<?php
$payload = [
    'name' => 'Example User',
    'active' => true,
];

$json = json_encode($payload, JSON_THROW_ON_ERROR);

$ch = curl_init('https://api.example.com/items');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $json,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Accept: application/json',
    ],
]);

$response = curl_exec($ch);

if ($response === false) {
    $error = curl_error($ch);
    curl_close($ch);
    throw new RuntimeException('Request failed: ' . $error);
}

$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException('API returned HTTP ' . $status);
}

Notes

Add the API's required authentication header without hardcoding secrets in source control. Handle rate limits, retries, and non-JSON error responses according to the API documentation.

Share this page Help other developers discover this resource.