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
- Python:
Requests— simple and popular HTTP library,HTTPX— async-capable HTTP client - JavaScript:
Axios— promise-based HTTP client,node-fetch— Fetch API for Node.js - Ruby:
HTTParty— simple HTTP client,Faraday— flexible HTTP library,RestClient— lightweight REST client - Java:
OkHttp— efficient HTTP client,Apache HttpClient— feature-rich library - C#:
RestSharp— simple REST client,Flurl— fluent HTTP library - Go:
resty— simple HTTP client,grequests— goroutine-based requests - PHP:
Guzzle— popular PHP HTTP client,Symfony HttpClient— component-based HTTP client