How to POST cURL Body from File in PHP | JSON, CSV, and More

Steps to POST cURL request with a body from a File in PHP

Sending a CURL request with body from file in PHP requires a few steps. You need to retrieve the content from your files, setup your curl request with curl_init, and include the CURLOPT_POSTFIELDS to the body content before executing with curl_exec.

  1. Initialize your cURL request with curl_init
  2. Open up your file content with file_get_contents
  3. Convert the file contents to a PHP array if not already.
  4. Setup your cURL Request Options array.
  5. Set CURLOPT_POST to true in options
  6. Set CURLOPT_POSTFIELDS to your PHP array from above
  7. Pass the options array to curl_setopt_array
  8. Send the cURL request with curl_exec
  9. Close the cURL request with curl_close
  10. Verify and validate response
  11. Continue processing.

Post cURL Body from File in PHP Code Snippet

<?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);
?>

Not completely sure about it? Read the article to learn every bit and piece of the cURL POST in PHP.

CSV PHP Code Examples and Learning Path

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.

Post cURL Body from File in PHP
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.

Firebase Logo
Firebase Logo

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.

Example#1

<?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);
 
?>

Example#2 

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.

Post cURL Body from File in PHP
User Created in Firebase Database

Option 1 | POST cURL Body from File using file_get_contents()

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
    }]
}

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

JSON Data in Database
JSON Data in Database

Option 2 | POST cURL Body from File in PHP using fgetcsv()

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

Example

<?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 Snippet

Post cURL Body from File in PHP
CSV to JSON Data in Database

Option 3 | POST cURL Body from File in PHP using CURLFILE

PHP CURLFILE is helpful when uploading a file with cURL CURLOPT_POSTFIELDS as the following example shows.

<?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

The following example reads more than one JSON file and sends them to the server. 

Example

<?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

Post cURL Body from File in PHP
Send Multiple Files with cURL

Voila! That’s it. Let’s move on to answer some FAQs.

Frequently Asked Questions

What is cURL?

cURL is a PHP library that allows users to send data to servers and supports over 25+ protocols. We use cURL to make requests using different protocols. Learn more about cURL in PHP: https://fuelingphp.com/php-curl-aws-ec2/

How to Install PHP cURL?

We can install cURL on the Windows, macOS, and Linux operating platforms. Learn how to install PHP cURL on AWS EC2 Linux: https://fuelingphp.com/php-curl-aws-ec2/

What is the HTTP POST Method?

POST is the HTTP method used to send data to servers. A few good examples from daily life would be filing a form on the web or making a comment on a social media platform. These are POST requests that send data to the server.

The server runs a backend program that may validate, transform or manipulate data before making calls to the database for persistence. 

What is the Difference between HTTP PUT and HTTP POST?

HTTP has four commonly used verbs – GET,  PUT, POST, and DELETE.

HTTP PUT

We call the HTTP PUT request method when we need to update a resource. It creates a new resource or replaces an existing one with a request. If the resource already exists in URO, PUT replaces it. In the case of no resource, PUT creates a new one. The HTTP PUT is idempotent and is not cacheable.

HTTP POST

The HTTP POST request method creates new resources on the server. It sends HTML forms, creates resources on the server, and uploads files. The HTTP POST is cacheable.

How to Send Body Message with cURL POST Request?

The POST request has a payload that mainly has a header and a body. The body may have data. Let’s revisit the last example and zoom in on the part where it initializes the data and sets it on the request’s body.

$data = '{
  "Id": 78912,
  "Name": "Carl Johnson",
  "Age": 20,
}';
 
 
//Set Body with $data
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

That’s how the POST request populates the body with the data.

Conclusion

Wrap Up

This article demonstrates how to POST cURL body from a file in PHP. The article starts from the bottom by explaining the fundamentals of how a POST request works and moves on to the top by explaining simple cURL POST with examples followed by three options to POST file using PHP cURL. 

Hope you’ve liked this article. Stay tuned for more at FuelingPHP.

Classes & Functions Mentioned

cURL – (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) cURL is a PHP library that uses liburl under the hood. The library comes with a bunch of functions. The functions that have been used in this article are the most commonly used functions of this library. The library as a whole is quite stable and performant. It has been available right from PHP 4.0.2 up to PHP 8.

curl_init – (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) Initializes a new cURL session and returns a cURL handler for use with the rest of the cURL functions.

curl_setopt –  (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) Set an option on the cURL handler.

curl_setopt_array – (PHP 5 >= 5.1.3, PHP 7, PHP 8) Sets options array on the cURL handler.

curl_exec  – (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) Execute a cURL session.

curl_close -(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) Closes a cURL session.

curl_error -(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) Returns the latest error string from the cURL session.

file_get_contents: (PHP 4.3, 5, 7, 8) This is a built-in PHP function that is available from PHP 4.3 and has been included in the latest version of PHP. Given its utility and stability, the function is here to stay with no chance of depreciation anytime soon.

json_encode: (PHP 5.2+, 7, 8) You will come across this function anytime you need to create a JSON string. It is commonly used to output your REST APIs. This is also a core function and deprecation is unlikely in the near or distant future.

Get deeper with PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.


© 2022 Confident.Systems