📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners HTTP Requests with cURL

HTTP Requests with cURL

6 min read
cURL sends HTTP requests to external APIs from PHP. Use curl_init(), curl_setopt(), and curl_exec() to make requests. Always verify SSL certificates and set timeouts to prevent scripts from hanging indefinitely.

cURL in PHP

// Basic GET
$ch = curl_init("https://api.github.com/users/torvalds");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["User-Agent: PHP"]);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
echo $data["name"];

// POST with JSON
function httpPost(string $url, array $data): array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($data),
        CURLOPT_HTTPHEADER     => [
            "Content-Type: application/json",
            "Authorization: Bearer " . $_ENV["API_TOKEN"]
        ],
    ]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($err) throw new RuntimeException("cURL error: $err");
    return json_decode($res, true);
}