PHP cURL

Last updated on

In PHP, there are plenty of times when you need to connect with other servers or APIs. That's where the use of cURL comes in with PHP. PHP cURL is a library that allows it to connect to and communicate with other servers or APIs using several protocols, such as HTTP, HTTPS, FTP, and many more.

This functionality is so crucial when you need to pull data from somewhere external, make requests to APIs, and even upload files.

In this article, I will be covering all you should know about PHP cURL: setting it up, making your first requests, handling responses, and troubleshooting common issues along the way.

What is PHP cURL?

PHP cURL is like a tool in PHP that helps you connect and talk to different servers, whether they’re using HTTP, FTP, or other protocols.

It is mostly used when you need to send or get data from APIs, letting you make requests to other servers right from your PHP code.

You can think of it as a way for your application to make HTTP requests—without needing a browser. That also means being able to access content supplied by other websites, fetch data from APIs, submit forms, or upload files—all within your PHP code.

To enable cURL in PHP, just follow these steps:

  1. Find your PHP configuration file: It’s usually called php.ini. If you’re using something like XAMPP, it’s likely in the php folder inside your XAMPP directory.
  2. Open php.ini and look for cURL: Open php.ini in any text editor and search for the line that says ;extension=curl. The semicolon (;) at the beginning of the line means cURL is turned off.
  3. Enable cURL: Simply remove the semicolon so it reads extension=curl. That’s it—this change tells PHP to load cURL.
  4. Restart your server: Save your changes and restart your server (like Apache or Nginx) to make sure it picks up the change. Once it’s back up, cURL should be good to go!

So, to check, you can create a quick PHP file with this code:

phpinfo();

Open that file in your browser, and if you see “cURL” in the info, you’re all set!

In the following part, I’ll walk you through setting up a cURL request in PHP, showing you how to configure the essential options to make sure your API call goes smoothly. You’ll learn how to build the request, set up options like headers and request types, and get everything working for a successful connection.

Setting Up a Basic PHP cURL Request

To set up a cURL request in PHP, you will start by opening a new session with curl_init(). Then, you will add the details with curl_setopt()—like the URL you are connecting to, any headers you need, and the request type, whether it’s a GET or POST.

When everything is ready, you can send the request with curl_exec(), then wrap it by closing the session with curl_close().

Here is an example:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://example.com/api/data");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Anyway, let’s check out some of the options you can use with PHP cURL and how each one can help you customize your request.

cURL Options

The PHP cURL gives you control over API requests. When you need to customize a request to fit just right, curl_setopt() is where the great happens. With it, you can adjust every little detail until your request is exactly what you need.

  • CURLOPT_URL sets the URL you’re trying to connect to. Simple, but it all starts here.
  • CURLOPT_RETURNTRANSFER is perfect when you want the response saved as a string, so you can work with it later. This is a go-to when you need the output without printing it right away.
  • CURLOPT_POST lets you make a POST request, which is essential when you’re sending data to an API.
  • CURLOPT_POSTFIELDS is like filling out a form; it holds the actual data you’re submitting in a POST request.
  • CURLOPT_HTTPHEADER is your way to add any custom headers. Think of it as the ID badge for your request, often used for things like authentication.

Knowing these options gives you the ability to shape requests that do exactly what you want.

So if you need to send data with a POST request the CURLOPT_POST and CURLOPT_POSTFIELDS are great options. So to add a header for an API that needs authorization, you can use CURLOPT_HTTPHEADER

Anyway, let's see how to use different types for HTTP request in PHP in the following section. 

Making Different Types of HTTP Requests with cURL

cURL enables you a lot of options with HTTP requests beyond the basic GET and POST. This is useful for RESTful APIs, where you may need different methods to retrieve, add, update, or delete data. Let's see the following list to learn more about the main request types:

  • GET Requests: By default, cURL does a GET request if you provide a URL without setting any specific method.
  • POST Requests: Use CURLOPT_POST along with CURLOPT_POSTFIELDS to send data through a POST request.
  • PUT Requests: To send a PUT request, set CURLOPT_CUSTOMREQUEST to "PUT," often with CURLOPT_POSTFIELDS to pass data.
  • DELETE Requests: For deleting data, set CURLOPT_CUSTOMREQUEST to "DELETE."

So, each of these options has its requirements of an API which help you manage all types of HTTP in PHP.

By moving onto the following section you will learn how to handling errors with cURL in PHP.

Handling Errors and Checking Responses

So, when you send request sometimes you got an error and other times it works. cURL gives you the ability to handle these situations. which means If the curl_exec() returns false, it means something went wrong, and you can use curl_error() to find more details about that error.

Here is an example: 

$curl = curl_init("https://example.com/api/data");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);

if ($response === false) {
    echo "cURL Error: " . curl_error($curl);
} else {
    echo "Response: " . $response;
}

curl_close($curl);

With error handling like this, you can catch unexpected issues—like network problems or incorrect URLs—without causing your application to crash.

In the following section, you will learn how to add headers into cURL in PHP.

Adding Headers in PHP cURL

When you work with APIs, headers an essential part, especially when authentication is required. Headers let you customize requests to match the API’s expectations, such as setting the content type or adding an authorization token.

$curl = curl_init("https://example.com/api/data");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer YOUR_TOKEN_HERE"
]);

$response = curl_exec($curl);
curl_close($curl);

Here, we are setting two headers: one for content type and another for authorization. This customization ensures that your request aligns with what the API requires.

Let's learn how to secure cURL request in PHP.

Securing Requests with SSL in cURL

If you have sensitive data, you must secure your requests with SSL. The SSL encrypts your data, keeping it safe from unauthorized access. By default, cURL will verify the remote server's SSL certificate.

For testing that, you might want to skip this by setting CURLOPT_SSL_VERIFYPEER to false, but remember to keep it enabled when you create your project in production.

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // Only for testing

SSL verification is crucial to ensuring data security. Let's move on to the following part to understand how to manage timeouts in PHP cURL.

Managing Timeouts in PHP cURL

Sometimes, the request might take longer than expected, and waiting endlessly is not ideal. cURL has options like CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT which lets you set time limits. CURLOPT_TIMEOUT limits the total time for the request, while CURLOPT_CONNECTTIMEOUT sets a time limit just for the connection phase.

Here are examples:

curl_setopt($curl, CURLOPT_TIMEOUT, 10); // Max 10 seconds for the entire request
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); // Max 5 seconds to connect

These settings help you to keep the application responsive and prevent it from hanging if a request takes too long.

Wrapping It Up

With PHP cURL, you are now ready to make your PHP applications connect to external APIs. From setting up requests to managing different HTTP methods, handling errors, adding headers, securing connections, and controlling timeouts. 

Each of these options helps you shape requests that meet the exact requirements of the API you are working with.

If you need to read more PHP tutorials, click here. Thank you for reading

Frequently Asked Questions (FAQs)

  • What is PHP cURL used for?

    PHP cURL is used to make HTTP requests from your PHP code, allowing you to connect with external APIs and servers. It lets you send data, retrieve data, and handle different types of HTTP requests like GET, POST, PUT, and DELETE.
  • How do I enable cURL in PHP?

    To enable cURL in PHP, locate the php.ini file, find the line with ;extension=curl, and remove the semicolon at the start to uncomment it. Save the file and restart your server. You can check if cURL is enabled by creating a PHP file with `
    phpinfo();
    and looking for “cURL” in the output.
  • How do I make a GET request with PHP cURL?

    To make a GET request, initialize a cURL session with curl_init(), set the URL with CURLOPT_URL, and set CURLOPT_RETURNTRANSFER to true to save the response. Here is an example:
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "https://example.com/api/data");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    echo $response;
    
  • How can I make a POST request with PHP cURL?

    For a POST request, set CURLOPT_POST to true and use CURLOPT_POSTFIELDS to specify the data. Here is an example:
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "https://example.com/api/data");
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, ["name" => "John", "age" => 25]);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    echo $response;
    
  • How can I set headers in a PHP cURL request?

    Use CURLOPT_HTTPHEADER to set custom headers for your request. This is especially helpful for authentication. Example:
    $curl = curl_init("https://example.com/api/data");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: Bearer YOUR_TOKEN_HERE"
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    echo $response;
    
  • How can I handle errors in PHP cURL?

    After executing a cURL request, you can check if curl_exec() returned false, which means there was an error. Use curl_error() to get the error message. Example:
    $curl = curl_init("https://example.com/api/data");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    
    if ($response === false) {
        echo "cURL Error: " . curl_error($curl);
    } else {
        echo "Response: " . $response;
    }
    
    curl_close($curl);
    
  • How do I secure my PHP cURL requests?

    To secure requests, cURL verifies SSL certificates by default. You can disable SSL verification for testing by setting CURLOPT_SSL_VERIFYPEER to false, but it is recommended to keep it enabled in production.
  • How can I set a timeout for PHP cURL requests?

    Use CURLOPT_TIMEOUT to limit the total request time and CURLOPT_CONNECTTIMEOUT to limit the connection phase. Example:
    $curl = curl_init("https://example.com/api/data");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
    $response = curl_exec($curl);
    curl_close($curl);
    echo $response;
    
  • Can PHP cURL handle different HTTP request methods?

    Yes, you can specify different HTTP methods using CURLOPT_CUSTOMREQUEST for methods like PUT and DELETE. For example, set CURLOPT_CUSTOMREQUEST to "PUT" for a PUT request or "DELETE" for a DELETE request.
Share on: