Skip to content
Home » 10 Top HTTP cURL Request Code Examples in 2023

10 Top HTTP cURL Request Code Examples in 2023

In this article, we discuss 10 HTTP cURL request questions. We will provide you with prompt answers regarding questions about how to send cURL to get request and post request, along with PHP code examples. We will also discuss how to attach and send a file using a cURL request and using Postman to send a cURL request.

curl http request

Table of Contents

In this article, we cover the following questions.

  1. What is a cURL Request
  2. What is cURL Used For?
  3. How to Setup & Use Curl in PHP
  4. How to Send cURL Get Request PHP Code Example?
  5. How to Send cURL Post Request PHP Code Example?
  6. How to POST JSON in a cURL Request?
  7. How to Send CSV Data in a cURL Request?
  8. How to Attach & Send a File in cURL Request?
  9. How to Use Postman to Send cURL Request?
  10. How to check file types in a cURL Request?

What is a cURL Request

CURL stands for client URL in PHP. In PHP, the cURL library is the most powerful extension of PHP. It allows users to create HTTP requests in PHP and also send and receive data through the URL. It makes communication easy between different websites and domains. We use cURL to make requests using different protocols.

The PHP cURL library supports multiple protocols, including HTTP, HTTPS, FTP, MQTT, etc.

what is cURL request

What is cURL Used For

cURL is used to make requests using different protocols in command lines or scripts to transfer data. It is also used in cars, television sets, routers, printers, audio equipment, mobile phones, tablets, settop boxes, and media players. It is the Internet transfer engine for thousands of software applications in over ten billion installations. cURL is used daily by virtually every Internet-using human on the globe.

How to Setup & Use Curl in PHP

To learn how to setup and use cURL in PHP, check out our article.

And if you want to install cURL libraries for PHP on AWS EC2 check out our article that. How to Install cURL for PHP on AWS Amazon Linux EC2

How to Send cURL Get Request PHP Code Example

Sending a cURL get request in PHP requires that you have cURL installed correctly on the server and that you are following the right procedural code. cURL will use the HTTP GET method by default when using the curl_exec function.

PHP cURL comes with a bunch of functions – see the documentation.

Some functions are fundamental for the lifecycle of a typical cURL request in PHP.

curl_init(); //Initializes a cURL session and returns a cURL handler.
curl_setopt(); //Sets up the options for the cURL session.
curl_exec(); //Executes the cURL session.
curl_close(); //Closes the session and deletes the variable (recommended use)

We can use the curl_init() and curl_exec() to send a cULR request in PHP.

Send a cURL GET Request in PHP using curl_init() and curl_exec()

Sending a basic GET request with PHP cURL requires a few lines of code. The following example sends a cURL GET Request using PHP.

$url = "https://jsonplaceholder.typicode.com/posts/1";
 
$curl = curl_init($url); //Initializes a cURL session and returns a cURL handler.
 
$response = curl_exec($curl); //Executes the cURL session.
 
curl_close($curl); //Closes the session and deletes the variable (recommended use)
 
echo $response;

We initialize a cURL handler with a URL in a few lines of code and execute the cURL session. Finally, the example prints the output to the console, which is as follows.

Output:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Send a PHP cURL GET Request with Parameters using curl_setopt()

PHP curl_setopt() adds many options to modify the cURL request. Check out the full list of options here. The following example revisits the last one – with some options now.

$url = "https://jsonplaceholder.typicode.com/posts/1";
 
$curl = curl_init($url); //Initializes a cURL session and returns a cURL handler.
 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //Converts output to a string.
curl_setopt($curl, CURLOPT_HEADER, false); //Excludes headers in the output.
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 50); //50 seconds of timeout
 
$response = curl_exec($curl); //Executes the cURL session.
 
curl_close($curl); //Closes the session and deletes the variable (recommended use)
 
echo $response;

The example adds several options before executing the cURL GET request in PHP. 

Send a PHP cURL GET Request with Parameters using curl_setopt_array()

An alternative way of binding options to the cURL handler is by passing in an array of options. This approach is suitable when you have to add many options and thus don’t want to call curl_setop() repeatedly.

Let’s refactor the last example using curl_setopt_array() this time.

$url = "https://jsonplaceholder.typicode.com/posts/1";
 
$curl = curl_init(); //Initializes a cURL session and returns a cURL handler.
 
curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => false,
    CURLOPT_CONNECTTIMEOUT => 50
]);
 
$response = curl_exec($curl); //Executes the cURL session.
 
curl_close($curl); //Closes the session and deletes the variable (recommended use)
 
echo $response;

Looks clean! Also, observe that the example passes in the URL in the options array. So, it is not absolutely necessary to pass the URL at the time of curl_init().

How to get cURL Response Headers in PHP

Using curl_getinfo() and headers offset, PHP gets the response header from the cURL transfer. The following example retrieves the header from the response.

$url = "https://jsonplaceholder.typicode.com/posts";
$curl = curl_init();
 
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
 
$response = curl_exec($curl);
 
$header_offset = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_offset);
 
echo json_encode($header);

Here’s the output.

HTTP/2 200 
date: Mon, 29 Aug 2022 18:30:54 GMT
content-type: application/json; charset=utf-8
x-powered-by: Express
x-ratelimit-limit: 1000
x-ratelimit-remaining: 999
x-ratelimit-reset: 1660077104
vary: Origin, Accept-Encoding
access-control-allow-credentials: true
cache-control: max-age=43200
pragma: no-cache
expires: -1
x-content-type-options: nosniff
etag: W/"6b80-Ybsq/K6GwwqrYkAsFxqDXGC7DoM"
via: 1.1 vegur
cf-cache-status: HIT
age: 11827
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
report-to: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=Z35VpEP7RCT%2Bm3UfWagbrpUXu28I1qUuuW0NWrsA4bId4K4lkJY01s0YnIo%2F6H6DGTSg32ZryBFezI0EcNwy%2BcI61dz32P26u9LZLMS6XtRoLb1W8AeW093T3yAw2OVROsef8Z2yS1PCmqPNKWFa"}],"group":"cf-nel","max_age":604800}
nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
server: cloudflare
cf-ray: 74275c4d5bcaa083-SIN
alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400

Call REST API using cURL in PHP

It is time to put together all we have learned so far and use a cURL GET request in PHP to fetch Posts from the API. Once we have the results, we can populate the HTML template.

Here’s the solution.

$url = "https://jsonplaceholder.typicode.com/posts";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
$response = curl_exec($curl);
 
if (curl_errno($curl)) {
    $response = curl_error($curl);
}
 
curl_close($curl);
 
 
echo "<html>
    <head>
        <title>Posts</title>
        <style>
            div {
                max-width: 500px;
                height: 150px;
                border: 3px solid black;
                margin: 1px 1px;
            }
        </style>
    </head>
    <body>";
 
    if(isset($error)) {
        echo "<div>Error in loading posts</div>";
    }
    else{
        $posts = json_decode($response, true);
        foreach($posts as $post)
        {
            echo "<div><p>".$post["title"]."</p><p>".$post["body"]."</p>"."</div>";
        }
    }
echo "</body>
</html>";

Running this script on a server renders the resulting HTML as follows.

curl http request

How to Send a cURL Post Request PHP Code Example

Now, in this section, we will learn how to send a cURL POST request in PHP. We will provide PHP code examples and explain how to send a cURL POST request in PHP.

How does a cURL POST Request Work?

A typical cURL post request would have a URL and a payload with headers and data. The cURL library will make an HTTP POST request to the specified URL. The URL points to the server and picks the request here.

Onwards, the server’s backend program retrieves the data from the request body and usually validates, transforms, or manipulates this data. Finally, the server calls a database driver or an ORM to help persist this data in the underlying database.

The following flow diagram shows this process visually.

curl post flow chart
cURL POST Flow Chart

Setup | Backend & Database

This article uses Firebase real-time database which is Google’s cloud-hosted NoSQL database with backend-as-a-service. Though it is not necessary to use Firebase, this article does it to quickly build a backend with a database rather than develop it from scratch.

curl http request

Simple cURL POST Request in PHP

A simple cURL request in PHP has the following steps:

  1. Initialize the cURL object with curl_init()
  2. Set the request parameters with curl_setopt()
  3. Send cURL POST request. 

The following example will use these steps to make a POST call with PHP cURL.

Curl PHP Post Request Example

<?php
 
//Server URL
$url = "https://fir-fuelingphp-default-rtdb.firebaseio.com/user.json";
 
//Initialize cURL extension
$curl = curl_init();
 
//Set URL
curl_setopt($curl, CURLOPT_URL, $url);
 
//Enable POST request
curl_setopt($curl, CURLOPT_POST, true);
 
//Set to return server response
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 
//Initialize Headers
$headers = array(
   "Accept: application/json",
   "Content-Type: application/json",
);
 
//Set Headers
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
 
//JSON string
$data = '{
  "id": 78912,
  "name": "Carl Johnson",
  "age": 20
}';
 
 
//Set Body with $data
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
 
//Run cURL request
$response = curl_exec($curl);
 
//If error occurs
if (curl_errno($curl)) {
  echo "CURL ERROR - " . curl_error($curl);
}
 
//If no errors
else {
  echo $response;
}
 
//Close to remove $curl from memory
curl_close($curl);
 
?>

Second Curl POST Request Example

The following example is equivalent to the one above except that it uses an options array to set them all at once using curl_setopt_array()

<?php
 
//Initialize cURL extension
$curl = curl_init();
 
//JSON string
$data = '{
    "id": 78912,
    "name": "Carl Johnson",
    "age": 20
  }';
   
 
//All options in an array
$options = [
    CURLOPT_URL => 'https://fir-fuelingphp-default-rtdb.firebaseio.com/user.json',
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Accept: application/json", "Content-Type: application/json"],
    CURLOPT_POSTFIELDS => $data
 
 ];
 
 //Set the Options array.
 curl_setopt_array($curl, $options);
 
//Run cURL request
$response = curl_exec($curl);
 
//If error occurs
if (curl_errno($curl)) {
  echo "CURL ERROR - " . curl_error($ch);
}
 
//If no errors
else {
  echo $response;
}
 
//Close to remove $curl from memory
curl_close($curl);
 
?>

The example initializes a cURL object with curl_init(). Secondly, it uses the curl_setopt()/curl_setopt_array()  to set the following parameters.

CURLOPT_URLRequest URL
CURLOPT_POSTEnable POST request
CURLOPT_RETURNTRANSFERFlag to return the server’s response
CURLOPT_HTTPHEADERSet headers
CURLOPT_POSTFIELDSSet data in the request body
cURL Options

The POST request reaches the Firebase backend, and the server then passes it to the database.

Output

Executing the above example returns the resource ID of the data stored in the database.

{"name":"-NFodF5YR46O8uyEAd18"}

Database Snippet

Here’s the data that was sent to the server and has now been stored in the database.

database
User Created in Firebase Database

How to POST JSON file in a cURL Request

The following example sends a JSON file as a request in the body using cURL POST in PHP.

First, it reads a file “file_1.json” using file_get_contents() and sends a post request to the server with the file’s JSON data.

The JSON File

Here is the JSON file.

{
   "Users":  [
    {
        "id": 1,
        "name": "Jack",
        "age": 22
    },
    {
        "id": 2,
        "name": "Solomon",
        "age": 32
    },
    {
        "id": 3,
        "name": "Liam",
        "age": 30
    }]
}

Post JSON File in cURL Request Code Example

<?php
 
//Initialise the cURL var
$curl = curl_init();
 
//Create a POST array with the file in it
$fileData = file_get_contents("file_1.json");
 
//All options in an array
$options = [
   CURLOPT_URL => 'https://fir-fuelingphp-default-rtdb.firebaseio.com/user.json',
   CURLOPT_POST => true,
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_HTTPHEADER => ["Accept: application/json", "Content-Type: application/json"],
   CURLOPT_POSTFIELDS => $fileData
 
];
 
//Set the Options array.
curl_setopt_array($curl, $options);
 
// Execute the request
$response = curl_exec($curl);
 
//If error occurs
if (curl_errno($curl)) {
  echo "CURL ERROR - " . curl_error($ch);
}
 
//If no errors
else {
  echo $response;
}
 
//Close to remove $curl from memory
curl_close($curl);
?>

Output

The output is a resource ID of the objects in the database.

{"name":"-NFobSTj0BiaCmMG8V_D"}

Database Snippet

curl http request
JSON Data in Database

How to Send CSV Data in a cURL Request

The following example uses fgetcsv() to read a CSV file. It appends the data to an array and then encodes that array as JSON data using json_encode(). Finally, it uses the same code shown in the example to send a CSV file to the cURL POST body. 
Learn more about how to read and write CSV files in PHP.

The CSV File

Id,Name,Age,Salary,Department
1,Anna,30,20000,Finance
2,Adam,25,15000,IT
3,Bob,32,25000,Finance
4,Cara,20,12000,Logistics
5,Daniel,28,27000,Engineering
6,Franklin,25,20000,Quality Assurance
7,Gorge,21,15000,IT
8,Kylie,20,10000,Engineering
9,Ivan,23,12000,Logistics
10,James,25,20000,Quality Assurance

Send CSV Data with cURL Example Code

<?php
 
$employees = [];
 
//Creates a new file employee_records.csv
$file = fopen('employees.csv', 'r'); //w is the flag for write mode.
 
if($file === false)
{
    die('Cannot open the file');
}
 
$header = fgetcsv($file);
 
//As long as there are records in the CSV file.
while(($row = fgetcsv($file)) !== false && count($row) > 1 )
{
    //Push the data record to employees array.
    array_push($employees, array_combine($header, $row));
}
 
//Closes the file.
fclose($file);
 
//Initialise the cURL var
$curl = curl_init();
 
 
//All options in an array
$options = [
   CURLOPT_URL => 'https://fir-fuelingphp-default-rtdb.firebaseio.com/user.json',
   CURLOPT_POST => true,
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_HTTPHEADER => ["Accept: application/json", "Content-Type: application/json"],
   CURLOPT_POSTFIELDS => json_encode($employees)
 
];
 
//Set the Options array.
curl_setopt_array($curl, $options);
 
// Execute the request
$response = curl_exec($curl);
 
//If error occurs
if (curl_errno($curl)) {
  echo "CURL ERROR - " . curl_error($ch);
}
 
//If no errors
else {
  echo $response;
}
 
//Close to remove $curl from memory
curl_close($curl);
 
?>

Output

The output is the resource ID for these JSON objects.

{"name":"-NFoiQpRs3ul4wU6Tl_3"}
database
CSV to JSON Data in Database

How to Attach & Send a File in cURL Request Code Example

Use the PHP CURLFILE class whenever you need to upload a file with cURL. You can pass the class into the CURLOPT_POSTFIELDS attribute when sending the request. You can see how it works in the following example.

<?php
 
$url = "https://fir-fuelingphp-default-rtdb.firebaseio.com/users.json";
$file = "file_2.json";
$upname = "users.json"; // File name to be uploaded as
 
//Read cURL file
$curlFile = new CURLFile($file, mime_content_type($file), $upname);
 
//Initialize cURL object
$curl = curl_init();
 
//Settings
$options = [
    CURLOPT_URL => $url,
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ["Accept: application/json", "Content-Type: application/json"],
    CURLOPT_POSTFIELDS => ["upload" => $curlFile]
];
 
//Set options
curl_setopt_array($curl, $options);
 
 
$response = curl_exec($curl);
 
//If error occurs
if (curl_errno($curl)) {
  echo "CURL ERROR - " . curl_error($curl);
}
 
//If no errors
else {
  echo $response;
}
 
//Close to remove $curl from memory
curl_close($curl);
?>

Send Multiple Files using cURL POST Request

You will want to use the CurlFIle class with several times when sending multiple files with cURL. It isn’t recommended to include them all into one cURL request as it may be prone to errors.

Multiple Files cURL Post Request PHP Code

<?php
 
function execURL($curl) {
    // Execute the request
    $response = curl_exec($curl);
   
    //If error occurs
    if (curl_errno($curl)) {
    echo "CURL ERROR - " . curl_error($ch);
    }
   
    //If no errors
    else {
    echo $response;
    }
}
 
 
//Initialise the cURL var
$curl = curl_init();
 
//Create a POST array with the file in it
$file_1 = file_get_contents("file_1.json");
 
$file_2 = file_get_contents("file_2.json");
 
//All options in an array
$options = [
   CURLOPT_URL => 'https://fir-fuelingphp-default-rtdb.firebaseio.com/user.json',
   CURLOPT_POST => true,
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_HTTPHEADER => ["Accept: application/json", "Content-Type: application/json"],
   CURLOPT_POSTFIELDS => $file_1
];
 
//Set the Options array.
curl_setopt_array($curl, $options);
 
execURL($curl);
 
//Set file_2 as data
curl_setopt($curl, CURLOPT_POSTFIELDS, $file_2);
 
execURL($curl);
 
//Close to remove $curl from memory
curl_close($curl);
?>

Output

{"name":"-NFoqtS6GZ2eRZRgS9OC"}{"name":"-NFoqtWECBXn9zYrSCn2"}

Database Snippet

curl http request
Send Multiple Files with cURL

How to Use Postman to Send cURL Request

If you are not comfortable using cURL in the terminal or prefer GUI apps instead, then Postman is a great choice. Postman has a friendly UI, which makes it easy to add/remove parameters, and changing things is more flexible.

 

Postman allows you to import curl commands, so you can easily copy any curl samples and paste them into Postman. Postman also enables users to save requests etc., which the cURL is not designed to do. In short, Postman allows a very modern and simpler workflow.

postman

Postman can help make cURL easier to use. 

  1. It offers an easier way to create cURL commands.
  2. Using the code snippet generator, you can also construct a request in Postman and convert it to cURL.
  3. In Postman, running cURL commands in a more user-friendly way.
  4. You can also import a cURL request into Postman and run it.

You can import and send a cURL request by using the following steps.

Step 1: Import cURL

Click on the Import button in the Postman toolbar to open the Import dialog window.

curl http request

In the Import window, click on the Paste Raw Text tab, which will show you a large textbox where you can paste a curl command.

import

After pasting the curl command, click on the Import button at the bottom of the dialog window. Postman will automatically convert the curl command into a Postman request.

Step 2: Send the Request

Importing the curl command will create a new Request tab in the main Postman window. The cURL request will already be filled in with the URL, headers, query parameters, request body, and other information from the curl command. All you need to do is to click on the Send button.

The response will display on the right-hand side or the bottom half of the screen, depending on whether you have Postman configured in a vertical or horizontal layout.

curl http request

In this article, we answered the top 10 cURL request questions for 2023, along with PHP code Examples. This article explains what a cURL request is and how it works. It also explains how to send a get cURL request and how to send cURL post request in PHP.

This article also focuses on how to post JSON files using a cURL request and how to send CSV data in a cURL request, and we hope you find this article helpful.

Continue Learning About cURL

This article is part of a larger series that we’ve written on the topic of using cURL in PHP. Feel free to browse through the articles to dig deeper into the topic.

Tags: