How to Make HTTP Requests with PHP cURL

This article provides a straightforward guide on how to perform external HTTP requests in PHP using the built-in cURL extension. You will learn the core steps required to initialize a cURL session, configure essential request options for both GET and POST methods, handle the API response, and properly close the connection to free up system resources.

The Basic cURL Workflow

Every cURL request in PHP follows a standard four-step lifecycle:

  1. Initialize the cURL session using curl_init().
  2. Configure the request options using curl_setopt() or curl_setopt_array().
  3. Execute the request using curl_exec().
  4. Close the session using curl_close() to free up system resources.

Making a GET Request

A GET request is used to retrieve data from a specified resource. Here is a simple implementation:

<?php
// 1. Initialize the cURL session
$ch = curl_init();

// 2. Set the options
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/users/octocat");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string
curl_setopt($ch, CURLOPT_USERAGENT, "PHP Script"); // Some APIs require a user-agent header

// 3. Execute the request and store the response
$response = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    // 4. Output the response
    echo $response;
}

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

Making a POST Request

A POST request is used to send data to a server to create or update a resource. You must specify the POST method and provide the payload.

<?php
$ch = curl_init();

// Define the data to be sent
$postData = [
    'username' => 'testuser',
    'email' => 'test@example.com'
];

curl_setopt($ch, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts");
curl_setopt($ch, CURLOPT_POST, true); // Set request method to POST
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // Format data as query string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

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

curl_close($ch);
?>

Sending JSON and Adding Headers

If you are interacting with modern REST APIs, you will often need to send JSON data and specify HTTP headers such as authorization tokens or content types.

<?php
$ch = curl_init();

$data = json_encode([
    'title' => 'foo',
    'body' => 'bar',
    'userId' => 1
]);

curl_setopt($ch, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Set headers for JSON content and Authorization
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_API_TOKEN'
]);

$response = curl_exec($ch);

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

curl_close($ch);
?>

Key cURL Options Reference