Blog › PHP · Published 2026-11-26

PHP cURL POST example with the options that matter

When PHP needs to call an external API, cURL is the built-in answer. The official php.net pages document the pattern; this guide assembles the POST case you reach for most, with the options that matter and the mistakes that waste hours.

The minimal POST

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.example.com/orders");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "item=keyboard&qty=2");

$response = curl_exec($ch);
curl_close($ch);

Three options do the work: CURLOPT_RETURNTRANSFER returns the response as a string instead of printing it, CURLOPT_POST makes it a POST, and CURLOPT_POSTFIELDS carries the body.

POSTFIELDS encoding, from the manual

A detail straight from the curl_setopt page: passing an array to CURLOPT_POSTFIELDS encodes the data as multipart/form-data, while passing a URL-encoded string sends application/x-www-form-urlencoded. If the API rejects your array payload, this is why: encode explicitly.

Sending JSON instead

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($order));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

Always set a timeout

Without CURLOPT_TIMEOUT your PHP worker waits as long as the remote server feels like. The manual notes CURLOPT_TIMEOUT_MS for sub-second limits, with a caveat: on Unix-like systems values under 1000 ms can trigger an immediate timeout bug, so prefer whole seconds.

Check for errors

if ($response === false) {
    $err = curl_error($ch); // DNS, TLS, timeout...
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

curl_exec returning false means a transport failure; an HTTP 500 is still a "successful" transfer you must check via the status code.

Related: prevent SQL injection in PHP before you store what the API sends back, and the same pattern in JavaScript.

Official sources

Need help with your project?
We build websites, systems and automation. Start your project WhatsApp

All articles