Sending and receiving data in JSON format is common when working with APIs. In PHP, you can use the cURL library to send HTTP requests, including sending JSON data in a POST request. In this article, we will explore how to POST JSON payload using the PHP cURL library in a step-by-step guide. We will also learn what JSON is and what JSON payload is.
Post JSON Payload in CURL PHP Code Example
<?php
// create the JSON payload as a PHP array
$data = array(
'name' => 'John',
'age' => 45,
'isMarried' => true,
'hobbies' => array('reading', 'traveling', 'cooking'),
'address' => array(
'street' => '123 Main St',
'city' => 'Tokyo',
'state' => 'CA',
'zip' => '12345'
)
);
// convert the PHP array to JSON format
$jsonPayload = json_encode($data);
// set the CURL options
$ch = curl_init('https://example.com/api');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute the CURL request
$response = curl_exec($ch);
curl_close($ch);
// handle the response from the server
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Response: ' . $response;
}
?>
Article Highlights
- We can post JSON payload using cURL library methods in PHP.
- Using cURL to post JSON payloads provides a reliable and efficient way to transfer data between servers, with the added benefits of flexibility, security, and ease of use.
- cURL provides built-in support for JSON, making it easy to send and receive JSON payloads without the need for additional libraries or tools.

Table of Contents
In this article, we will cover the following topics.
- What is JSON?
- What is JSON Payload?
- Step-by-step guide to post JSON payload using PHP cURL.
- How to post JSON payload in CURL with PHP Explored.
What is JSON?
JSON stands for JavaScript object notation. The JSON data is written as name/value pairs, and it is basically a lightweight data-interchange format that is very easy to parse and generate.
JSON is based on two basic structures:
- Object: It is a collection of key/value pairs (i.e., key: value). And each object begins with a left curly bracket { and then ends with a right curly bracket }. And the multiple key/value pairs are separated by a (comma,).
- Array: An ordered list of values starts with a left bracket [ and ends with a right bracket ]. The values in an array are separated by a (comma,).
In JSON data, the keys are always strings, but the value can be a string, number, true or false, null, or even an object or an array. Strings must be enclosed in double quotes ” and can contain escape characters such as \n, \t, and \.
A JSON object may look like this:
{
"Profile": {
"name": "John",
"Last Name": "Stones",
"Born": 1995,
"Gender": "Male"
}
}
What is JSON Payload?
JSON payload is a piece of data that is formatted using the JavaScript Object Notation (JSON) syntax and is typically used for sending data between client-server applications over the internet. JSON is a lightweight data-interchange format that is easy for humans to read and write and is also easy for machines to parse and generate.
The JSON payloads can contain various data types such as strings, numbers, booleans, arrays, and objects. They are commonly used in web APIs, where a client sends a request to a server with a JSON payload containing data needed for the request. Similarly, the server can respond with a JSON payload containing the requested data.
Here is an example of a simple JSON payload:
{
"name": "John",
"age": 45,
"isMarried": true,
"hobbies": ["reading", "traveling", "cooking"],
"address": {
"street": "12 Main St",
"city": "New York",
"state": "CA",
"zip": "2400"
}
}
The above JSON payload example represents an object with properties such as name, age, isMarried, hobbies, and address. The address property is an object with its street, city, state, and zip code properties.
Step-by-step guide to post JSON payload using PHP cURL
Using the below steps, you can post a JSON payload with the PHP cURL library.
Step 1: Set the URL and JSON data
In the first step, we will set the URL to which we want to send the request and the JSON data that we want to send in the request body. For this example, we will use the following sample JSON data.
// create the JSON payload as a PHP array
$data = array(
'name' => 'John',
'age' => 45,
'isMarried' => true,
'hobbies' => array('reading', 'traveling', 'cooking'),
'address' => array(
'street' => '123 Main St',
'city' => 'Tokyo',
'state' => 'CA',
'zip' => '12345'
)
);
// convert the PHP array to JSON format
$jsonPayload = json_encode($data);
In the above example, we created an array of data and then encoded it into a JSON string using the json_encode() function in PHP.
Step 2: Set the cURL options
In the next step, we need to set these cURL options for the request( the URL, request method, and request body). The following example code shows how to set the cURL options.
// set the CURL options
$ch = curl_init('https://example.com/api');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
In the above code example, we set the following options:
- CURLOPT_POST: We set it to true to return the response as a string instead of outputting it directly to the screen.
- CURLOPT_CUSTOMREQUEST: We set it to “POST” to specify that we’re sending a POST request.
- CURLOPT_POSTFIELDS: We set it to the JSON data we want to send in the request body.
- CURLOPT_HTTPHEADER: We set it to an array of headers, including the Content-Type header to specify that we are sending JSON data and the Content-Length header to specify the length of the JSON data.
Step 3: Send the request and handle the response
In the final step, we send the request using the curl_exec() function and handle the response. The below code example shows how to do this.
// execute the CURL request
$response = curl_exec($ch);
curl_close($ch);
// handle the response from the server
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Response: ' . $response;
}
Complete PHP code to post JSON payload using PHP cURL
Now, let’s combine the above codes, and we will get a fully functional PHP code that can post JSON payload to remote APIs.
<?php
// create the JSON payload as a PHP array
$data = array(
'name' => 'John',
'age' => 45,
'isMarried' => true,
'hobbies' => array('reading', 'traveling', 'cooking'),
'address' => array(
'street' => '123 Main St',
'city' => 'Tokyo',
'state' => 'CA',
'zip' => '12345'
)
);
// convert the PHP array to JSON format
$jsonPayload = json_encode($data);
// set the CURL options
$ch = curl_init('https://example.com/api');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// execute the CURL request
$response = curl_exec($ch);
curl_close($ch);
// handle the response from the server
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Response: ' . $response;
}
?>
Note that the above code example assumes you have the CURL extension enabled in your PHP installation. If you do not have the extension enabled, you can enable it in your PHP configuration file (php.ini) or install it using a package manager.
How to post JSON payload in CURL with PHP
Set the cURL options with URL and JSON data to post a request with cURL using a JSON payload. The CURLOPT_POSTFIELDS option will allow for the payload, and the CURLORPT_HTTPHEADER should include “Content-Type: application/json”.
This article explained how to POST JSON payload with PHP cURL in a step-by-step guide. By setting the URL and JSON data, setting the cURL options, sending the request, and handling the response, you can easily send a JSON payload in a POST request using PHP cURL.
This article explains what JSON is and what JSON payload is. This article also describes all the steps required to post JSON payload using the PHP cURL.
Continue Learning About cURL
This article is part of a more extensive series on using cURL in PHP. Feel free to browse through the articles to dig deeper into the topic.
- What is cURL used for
- Install cURL Libraries for PHP on AWS EC2 From Start to Finish
- POST cURL Body from File: PHP Code Examples ( JSON, CSV )
- How to Send a cURL GET Request
- 10 HTTP cURL Request Questions Answered
- Fetching Data from a REST API in PHP
- How to Post JSON Payload in cURL
- cURL Requests: Add Authorization Headers
- using cURL with Bearer Authorization Tokens
- using cURL with Self-Signed Certificates
Learn the Fundamentals of Good Web Development
Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.