cURL is PHP’s built-in library for making HTTP requests — calling REST APIs, downloading files, authenticating with external services, and scraping web pages. It is a core skill for any PHP developer building applications that communicate with the outside world. This guide covers everything from a basic GET request to authenticated API calls with proper error handling.
Table of Contents
What is cURL in PHP?
cURL (Client URL Library) is a library that lets PHP code act as an HTTP client — making requests to URLs just as a browser would, but from server-side PHP code. It supports GET, POST, PUT, DELETE, and all other HTTP methods, along with headers, authentication, cookies, file uploads, and SSL.
PHP includes cURL as a built-in extension (enabled by default on most hosting plans). Check availability:
var_dump(function_exists('curl_init')); // bool(true) = cURL is available
Basic GET Request
<?php
function http_get(string $url): string {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true, // Return response as string
CURLOPT_FOLLOWLOCATION => true, // Follow redirects
CURLOPT_TIMEOUT => 30, // 30 second timeout
CURLOPT_USERAGENT => 'CampCodes-PHP/1.0',
]);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new RuntimeException("cURL error: $error");
}
return $response;
}
$html = http_get('https://example.com');
echo strlen($html) . ' bytes received';
GET Request to a JSON API
function api_get(string $url, array $params = []): array {
if (!empty($params)) {
$url .= '?' . http_build_query($params);
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new RuntimeException("cURL error: $error");
}
if ($httpCode >= 400) {
throw new RuntimeException("HTTP error $httpCode");
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException("JSON decode error: " . json_last_error_msg());
}
return $data;
}
// Example: fetch posts from a REST API
$posts = api_get('https://jsonplaceholder.typicode.com/posts', ['_limit' => 5]);
foreach ($posts as $post) {
echo $post['title'] . PHP_EOL;
}
POST Request with JSON Body
function api_post(string $url, array $data, string $token = ''): array {
$json = json_encode($data);
$headers = ['Content-Type: application/json', 'Content-Length: ' . strlen($json)];
if ($token !== '') {
$headers[] = "Authorization: Bearer $token";
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ['status' => $httpCode, 'body' => json_decode($response, true)];
}
// Create a new post via API:
$result = api_post(
'https://jsonplaceholder.typicode.com/posts',
['title' => 'My Post', 'body' => 'Content here', 'userId' => 1]
);
echo "Status: {$result['status']}, ID: {$result['body']['id']}";
POST Form Data (x-www-form-urlencoded)
$ch = curl_init('https://example.com/login');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query(['username' => 'admin', 'password' => 'secret']),
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
]);
$response = curl_exec($ch);
curl_close($ch);
Custom HTTP Methods (PUT, PATCH, DELETE)
// PUT request:
$ch = curl_init('https://api.example.com/users/1');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => json_encode(['name' => 'Updated Name']),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);
// DELETE request:
$ch = curl_init('https://api.example.com/users/1');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Authentication Methods
// Bearer token (most common for REST APIs):
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer {$token}"]);
// Basic auth:
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
// Or equivalently:
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Basic ' . base64_encode("$username:$password")]);
// API key in header:
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-API-Key: {$apiKey}", "Accept: application/json"]);
File Download with cURL
function download_file(string $url, string $save_path): void {
$fp = fopen($save_path, 'wb');
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_FILE => $fp, // Write to file handle
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 300, // 5 minutes for large files
]);
curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
fclose($fp);
if ($error) {
unlink($save_path);
throw new RuntimeException("Download failed: $error");
}
}
download_file('https://example.com/document.pdf', '/tmp/document.pdf');
Error Handling Best Practices
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
if (curl_errno($ch)) {
// Network-level error (connection refused, DNS failure, timeout)
$error = curl_error($ch);
curl_close($ch);
throw new RuntimeException("cURL error: $error");
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
$sizeDown = curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
curl_close($ch);
if ($httpCode === 401) throw new RuntimeException('Unauthorized — check API credentials');
if ($httpCode === 404) throw new RuntimeException('Resource not found');
if ($httpCode === 429) throw new RuntimeException('Rate limit exceeded — slow down requests');
if ($httpCode >= 500) throw new RuntimeException("Server error: HTTP $httpCode");
cURL vs file_get_contents vs Guzzle
| Method | Use Case | Pros | Cons |
|---|---|---|---|
| cURL | Any HTTP request | Full control, no dependencies | Verbose configuration |
| file_get_contents | Simple GET only | One line of code | No headers, no POST, no error details |
| Guzzle | Complex API integrations | Clean API, async support, PSR-7 | Requires Composer |
Use raw cURL for simple scripts without Composer. Use Guzzle (composer require guzzlehttp/guzzle) for complex API integrations in proper applications.
Frequently Asked Questions
Why does curl_exec() return false?
It returns false on a network-level error (not an HTTP error). Check curl_error($ch) for the specific message. Common causes: DNS resolution failure, connection refused, SSL certificate error, or timeout. Set CURLOPT_SSL_VERIFYPEER => false temporarily to check if SSL is the issue (never leave this off in production).
How do I follow HTTP redirects with cURL?
Set CURLOPT_FOLLOWLOCATION => true. By default, cURL does not follow 301/302 redirects — it returns the redirect response itself. With FOLLOWLOCATION, it automatically follows up to CURLOPT_MAXREDIRS (default 5) redirects.
How do I debug cURL requests?
curl_setopt($ch, CURLOPT_VERBOSE, true); // Print verbose output
curl_setopt($ch, CURLOPT_STDERR, fopen('php://output', 'w')); // To screen
// Or use curl_getinfo() after execution to see all request/response metadata
Conclusion
PHP cURL is the standard way to make HTTP requests from PHP. The core pattern — curl_init(), curl_setopt_array(), curl_exec(), curl_close() — handles every use case from simple GET requests to authenticated multipart file uploads. Wrap your cURL calls in reusable functions with proper error handling, and you have a solid HTTP client that works without any additional dependencies.
Next Step for Your Project Journey
Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

