PHP

Simple cURL GET with Timeout

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A no-dependency HTTP GET helper with sensible defaults: short timeout, follow redirects, return body as string, throw on transport error. Pass extra headers as a simple associative array.
PHP
Raw
<?php
function httpGet(string $url, array $headers = [], int $timeoutSec = 10): string {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS      => 5,
        CURLOPT_CONNECTTIMEOUT => $timeoutSec,
        CURLOPT_TIMEOUT        => $timeoutSec,
        CURLOPT_USERAGENT      => 'myapp/1.0',
        CURLOPT_HTTPHEADER     => array_map(
            fn($k, $v) => "$k: $v",
            array_keys($headers), $headers
        ),
    ]);
    $body = curl_exec($ch);
    if ($body === false) {
        $err = curl_error($ch);
        curl_close($ch);
        throw new RuntimeException("HTTP GET failed: $err");
    }
    curl_close($ch);
    return $body;
}

$json = httpGet('https://api.example.com/users', ['Accept' => 'application/json']);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.