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);PUT request example
Replacing a resource with PUT:
$ch = curl_init('https://api.example.com/users/123');
$data = json_encode(['name' => 'John Updated', 'email' => 'john.new@example.com']);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
]);
$response = curl_exec($ch);
curl_close($ch);DELETE request example
Deleting a resource:
$ch = curl_init('https://api.example.com/users/123');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_HTTPHEADER => ['Authorization: Bearer YOUR_TOKEN']
]);
$response = curl_exec($ch);
curl_close($ch);Error handling
Check curl_errno($ch) and curl_error($ch) for errors. Verify the HTTP response code with curl_getinfo($ch, CURLINFO_HTTP_CODE) before processing.
Try it in Send Web Request
PHP's cURL is similar to the command-line curl. Use Send Web Request to test the request in your browser first.
Open Send Web RequestOther 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 (Golang):
resty— simple HTTP client,grequests— goroutine-based requests - PHP:
Guzzle— popular PHP HTTP client,Symfony HttpClient— component-based HTTP client