Introduction
In modern web development, applications often need to communicate with external servers or APIs. Whether it’s fetching data from a third-party service, sending form data, or integrating payment gateways, making HTTP requests is essential.
PHP provides a powerful library called cURL (Client URL Library) that allows developers to send and receive data using various protocols such as HTTP, HTTPS, FTP, and more.
What is PHP cURL?
PHP cURL is a library that enables communication between PHP applications and external servers using URLs. It allows you to perform HTTP requests such as:
- GET (retrieve data)
- POST (send data)
- PUT, DELETE (advanced API operations)
cURL works by initializing a session, setting options, executing the request, and then closing the session.
Why it is used
PHP cURL is widely used for:
1. API Integration
Fetch or send data to third-party APIs (e.g., payment gateways, weather APIs).
2. Web Scraping
Extract data from websites.
3. File Download
Download images, PDFs, or other files.
4. Form Submission
Send form data programmatically.
5. Authentication
Handle secure requests with tokens or headers.
Syntax
Basic cURL Workflow
<?php
// Initialize cURL
$ch = curl_init();
// Set options
curl_setopt($ch, CURLOPT_URL, "https://api.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute request
$response = curl_exec($ch);
// Close session
curl_close($ch);
// Output response
echo $response;
?>
- CURLOPT_URL → URL to send request
- CURLOPT_RETURNTRANSFER → Return response as string
- CURLOPT_POST → Enable POST request
- CURLOPT_POSTFIELDS → Data to send
- CURLOPT_HTTPHEADER → Custom headers
- CURLOPT_TIMEOUT → Request timeout
Examples:
You will see many examples.
Example 1: GET Request
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response
?>
Example 2: POST Request
<?php
$ch = curl_init();
$data = [
"name" => "Gaurav",
"email" => "gaurav@example.com"
];
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/users");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Example 3: Send JSON Data
<?php
$ch = curl_init();
$data = json_encode([
"name" => "Gaurav",
"age" => 28
]);
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Content-Length: " . strlen($data)
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
Example 4: Handling Errors
<?php
$ch = curl_init("https://api.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(curl_errno($ch)) {
echo "Error: " . curl_error($ch);
}
curl_close($ch);
?>
Real-Life Example
Example 1: Fetch Weather Data from API
<?php
$ch = curl_init();
$url = "https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=Delhi";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
echo "Temperature: " . $data['current']['temp_c'] . "°C";
?>
Example 2: Payment Gateway Integration
<?php
$ch = curl_init();
$data = [
"amount" => 1000,
"currency" => "INR"
];
curl_setopt($ch, CURLOPT_URL, "https://payment-api.com/create");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer YOUR_TOKEN",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response
?>
Example 3: File Download
<?php
$ch = curl_init("https://example.com/image.jpg");
$file = fopen("image.jpg", "w");
curl_setopt($ch, CURLOPT_FILE, $file);
curl_exec($ch);
curl_close($ch);
fclose($file);
echo "File downloaded successfully!";
?>
Common Mistakes
1. Not Enabling cURL Extension
Ensure php_curl is enabled in php.ini.
2. Forgetting CURLOPT_RETURNTRANSFER
Without it, response will not be stored.
3. Not Handling Errors
Ignoring curl_error() can cause debugging issues.
4. Incorrect Headers
Missing or wrong headers can break API requests.
5. Not Closing cURL Session
Always use curl_close().
6. Sending Wrong Data Format
APIs may require JSON instead of form data.
Conclusion
PHP cURL is a powerful and flexible tool for making HTTP requests and interacting with external services. It plays a vital role in modern web development, especially when working with APIs, payment gateways, and third-party integrations.
By mastering cURL functions such as curl_init(), curl_setopt(), and curl_exec(), developers can build robust and scalable applications that communicate effectively with other systems.