PHP

cURL POST JSON

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Post a JSON body with the right Content-Type header and parse the response. Returns the decoded body or throws on a non-2xx response.
PHP
Raw
<?php
function postJson(string $url, array $body, array $extraHeaders = [], int $timeout = 15): array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($body, JSON_THROW_ON_ERROR),
        CURLOPT_HTTPHEADER     => array_merge([
            'Content-Type: application/json',
            'Accept: application/json',
        ], $extraHeaders),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => $timeout,
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    if ($code < 200 || $code >= 300) {
        throw new RuntimeException("POST failed: HTTP $code — $resp");
    }
    return json_decode($resp, true, 512, JSON_THROW_ON_ERROR);
}

$user = postJson('https://api.example.com/users', ['name' => 'Alice', 'email' => 'a@x.com']);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.