PHP cURL: GET and POST requests with JSON, headers and error handling
Checkcraft is a desktop app for checking APIs and logs without code, with a free edition. Download, no sign-up →
The cURL extension is the standard way to call an external API from PHP. A request is built from options: URL, method, headers, body, timeouts. What people often forget: return the response as a string, and check the status code and the connection error separately. Below is a ready function and the options explained.
Main options
CURLOPT_RETURNTRANSFER returns the response as a string instead of printing it. CURLOPT_HTTPHEADER takes an array of header strings. CURLOPT_POSTFIELDS sets the body: for JSON pass a json_encode string, not an array, or a form is sent. CURLOPT_TIMEOUT limits request time.
Two different errors
If curl_exec returned false the request failed: read curl_error and curl_errno; the codes match the curl tool. If a response arrived, check the code with curl_getinfo and CURLINFO_RESPONSE_CODE: 4xx and 5xx are not cURL errors and slip through unchecked.

Check the request outside PHP
When it is unclear whether the code or the server is at fault, repeat the same request with command-line curl with the same headers and body. If curl gets the right answer, the PHP request is built wrong: usually an array instead of a JSON string or a lost header.
A ready API request function
<?php
function apiRequest(string $method, string $url, ?array $body = null, string $token = ''): array
{
$ch = curl_init($url);
$headers = ['Accept: application/json'];
if ($token !== '') {
$headers[] = 'Authorization: Bearer ' . $token;
}
if ($body !== null) {
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
}
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 30,
]);
$raw = curl_exec($ch);
if ($raw === false) {
throw new RuntimeException('cURL error ' . curl_errno($ch) . ': ' . curl_error($ch));
}
$code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($code >= 400) {
throw new RuntimeException("HTTP $code: " . mb_substr($raw, 0, 300));
}
return json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
}
$order = apiRequest('POST', 'https://api.example.com/v1/orders', ['sku' => 'MON-24', 'qty' => 2], getenv('API_TOKEN'));The function separates a connection error from an HTTP error and parses JSON with an exception on bad format. In PHP 8 curl_close is not needed; the handle is freed automatically.

Common mistakes
- The response prints to the page. CURLOPT_RETURNTRANSFER is off.
- The server gets a form instead of JSON. An array went to CURLOPT_POSTFIELDS instead of json_encode.
- A 4xx went unnoticed. The code was not checked with curl_getinfo.
- SSL certificate problem. php.ini lacks curl.cainfo with root certificates. Do not disable CURLOPT_SSL_VERIFYPEER.
If json_decode fails, look at the start of the response: often it is an HTML error page. See JSON parse error.
More on curl
Section overview and all guides: curl command cheat sheet: flags and examples for APIs.
- Webhook: what it is, how it works and how to test it
- curl GET request: parameters, response headers and status code
- cURL examples: GET and POST requests with JSON on Linux, Windows and PowerShell
- Headers in curl: Content-Type application/json, Accept and multiple -H
- curl with authorization: Bearer token, Basic, API key and headers
Frequently asked questions
How do I POST JSON with PHP cURL?
json_encode string in CURLOPT_POSTFIELDS, Content-Type header, CURLOPT_RETURNTRANSFER.
How do I get the status code?
curl_getinfo($ch, CURLINFO_RESPONSE_CODE).
How do I handle errors?
curl_error when curl_exec returns false; check the HTTP code separately.
Repeat this on your own API
Checkcraft is a desktop app that saves API response checks without code and shows what did not match. Start with a sample, then use your own sanitized data. Free runs on Windows and Linux with no time limit.
Download FreeDownload and first runNo sign-up or email needed, the archive is ready in a couple of minutes. See the edition limits.
References
Start with the linked example and compare its result with your own test requirement.