Skip to content
CheckcraftDownload
Practical workflow

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.

Checkcraft ·

Get help with your first test →

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.

API call diagram: method and URL, headers, body, status and response body, logs and database

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.

Layers of an API call check: status, headers, body, calculations, logs, database

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.

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.

Next step

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 run

No sign-up or email needed, the archive is ready in a couple of minutes. See the edition limits.

References

PHP: cURL extension

Start with the linked example and compare its result with your own test requirement.

Ask a person

Get help with your first test

Tell us what you want to test or where you got stuck. We can help you start Checkcraft, choose an example and understand your first run. You can ask before downloading.

The Telegram group is public: do not post passwords, tokens or confidential work data. A description of your task is enough to start.

You can also email us support@checkcraft.ru

No account required. We will reply by email. This is a support request, not a newsletter subscription.