How to Make cURL Requests with PHP: A Complete Tutorial

How to Make cURL Requests with PHP: A Complete Tutorial

cURL is a powerful tool in PHP used to send HTTP requests and interact with REST APIs. Whether you’re fetching data from a remote server or sending data via POST, cURL is essential in modern PHP development.

In this tutorial, you’ll learn:

  • What cURL is and why it’s useful

  • How to make GET, POST, PUT, and DELETE requests

  • How to handle responses and errors

  • Bonus: Using cURL with JSON APIs

 

 

What is cURL?

cURL stands for Client URL, and it allows PHP to communicate with other servers using various protocols, such as HTTP, HTTPS, FTP, etc. It’s especially useful when working with APIs or integrating external services.

Prerequisites

Make sure cURL is enabled in your PHP installation. You can check this by running:


phpinfo();


Look for cURL support => enabled. If it’s not enabled, install or enable the cURL extension:

  • On Ubuntu: sudo apt install php-curl

  • On Windows: uncomment extension=curl in your php.ini

 

Making a GET Request

Here’s how to send a simple GET request:


<?php
$url = "https://api.example.com/data";

// Initialize cURL session
$ch = curl_init($url);

// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute and get the response
$response = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
echo "Response: " . $response;
}

// Close the session
curl_close($ch);
?>


Making a POST Request

To send data (e.g. form data or JSON), use CURLOPT_POST and CURLOPT_POSTFIELDS:


<?php
$url = "https://api.example.com/create";

$data = [
"name" => "John Doe",
"email" => "[email protected]"
];

$ch = curl_init($url);
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);

if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
echo "Response: " . $response;
}

curl_close($ch);
?>


Sending JSON Data with cURL

When working with APIs, you often send data as JSON:


<?php
$url = "https://api.example.com/json-endpoint";

$data = [
"username" => "admin",
"password" => "12345"
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($data))
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
echo "Response: " . $response;
}

curl_close($ch);
?>


Making PUT and DELETE Requests

To send other HTTP methods like PUT or DELETE, use CURLOPT_CUSTOMREQUEST:

PUT Request


curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");


DELETE Request


curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

Use CURLOPT_POSTFIELDS as needed to send data.

 

Handling Response Headers

To get both headers and body:

</p>
<p data-start="3272" data-end="3301">curl_setopt($ch, CURLOPT_HEADER, true);</p>
<p data-start="3272" data-end="3301">

To get headers separately:

</p>
<p data-start="3272" data-end="3301">curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$headers) {
$len = strlen($header);
$headers[] = $header;
return $len;
});</p>
<p data-start="3272" data-end="3301">

Handling Errors Gracefully

Use curl_error() and curl_errno() to debug failures. Always close your session with curl_close($ch).

Example: Complete JSON POST with Response Handling

</p>
<?php
$url = "https://api.example.com/login";
$data = ["username" => "test", "password" => "secret"];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

$response = curl_exec($ch);

if ($response === false) {
echo "Curl error: " . curl_error($ch);
} else {
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "HTTP Status Code: $http_code\n";
echo "Response: $response";
}

curl_close($ch);
?>
<p data-start="3593" data-end="3699">

Summary

PHP cURL allows you to:

  • Send HTTP requests (GET, POST, PUT, DELETE)

  • Handle APIs and JSON data

  • Manage headers and errors

Mastering cURL opens the door to building robust PHP applications that communicate effectively with APIs and remote services.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *