Skip to main content
Send Web Request

How to Make an HTTP Request with PHP

PHP can make HTTP requests with cURL or the Guzzle library. cURL is built-in; Guzzle is popular for more complex needs.

GET request example

Making a GET request to fetch data with custom headers:

$ch = curl_init('https://api.example.com/users');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Authorization: Bearer YOUR_TOKEN'
    ]
]);
$response = curl_exec($ch);
$data = json_decode($response);
curl_close($ch);

POST request example

Making a POST request to send JSON data:

$ch = curl_init('https://api.example.com/users');
$data = json_encode(['name' => 'John', 'email' => 'john@example.com']);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json']
]);
$response = curl_exec($ch);
curl_close($ch);

Other libraries you can try