A PHP script often needs to talk to another service — a payment provider, a weather API, a third-party service's data. cURL is PHP's built-in way to make that outgoing HTTP request.
$ch = curl_init('https://api.example.com/users');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);| Option | What it does |
|---|---|
| CURLOPT_RETURNTRANSFER | Returns the response as a string instead of printing it directly |
| CURLOPT_POST | Sends the request as POST instead of GET |
| CURLOPT_POSTFIELDS | The data to send in a POST request |
| CURLOPT_HTTPHEADER | An array of custom headers, like Content-Type or Authorization |
| CURLOPT_TIMEOUT | Maximum seconds to wait before giving up |
$payload = json_encode(['name' => 'Sam', 'email' => 'sam@example.com']);
$ch = curl_init('https://api.example.com/users');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiToken,
]);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);A network failure — a timeout, a DNS error — needs to be checked for separately from a bad HTTP status code.
if (curl_errno($ch)) {
echo 'cURL error: ' . curl_error($ch);
} elseif ($statusCode !== 200) {
echo "Request failed with status $statusCode";
}Guzzle, for real projects
The Guzzle package (installed via Composer, from the earlier lesson) wraps cURL in a much friendlier API and is the standard choice for a real project — raw cURL is still worth understanding since it's what Guzzle itself uses underneath.