Php

How to POST JSON Data With PHP cURL

19 September 2026 · 10 min read

How to POST JSON Data With PHP cURL

In today’s interconnected digital landscape, exchanging data between applications is a fundamental requirement. PHP, with its versatile cURL library, provides a powerful mechanism for achieving this, especially when dealing with JSON (JavaScript Object Notation), the ubiquitous data-interchange format. Mastering how to POST JSON data with PHP cURL is essential for developers building APIs, interacting with web services, or automating data transfers. This guide will walk you through the process step-by-step, ensuring you understand the core concepts and can implement robust solutions in your PHP projects. We’ll cover everything from setting up the cURL options to handling responses effectively, empowering you to seamlessly integrate your PHP applications with various JSON-based services.

Understanding JSON and cURL

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It’s built on two structures: a collection of name/value pairs (objects) and an ordered list of values (arrays). Its simplicity and universality have made it the de facto standard for API communication. cURL, on the other hand, is a command-line tool and a library for transferring data with URLs. PHP’s cURL extension allows you to make HTTP requests, including POST requests, which are crucial for sending data to a server. By combining these two technologies, you can efficiently send JSON data from your PHP applications to external services or APIs.

Before diving into the code, it’s crucial to understand the HTTP request-response cycle. A POST request sends data to a server to create or update a resource. The server processes this data and sends back a response, which may include a status code indicating success or failure, along with additional data. When posting JSON, you’re essentially packaging data in a structured format and sending it to the server for processing. The receiving server then needs to be configured to correctly interpret the JSON data being sent. The popularity of JSON for data transmission is evident; according to a Statista report, JSON is used in over 90% of web APIs [1].

The combination of PHP’s cURL and JSON presents a potent solution for modern web development needs. You gain the ability to interact with a vast array of APIs and web services that rely on JSON for data exchange. This interaction allows for the development of applications that can aggregate data from multiple sources, automate processes, and seamlessly integrate with other systems. Understanding the nuances of how to POST JSON data with PHP cURL unlocks the potential to build sophisticated and interconnected web applications.

Setting Up cURL Options for JSON POST

The core of posting JSON data with PHP cURL lies in properly configuring the cURL options. This involves initializing the cURL session, setting the necessary headers, specifying the POST data, and handling the response. A crucial step is setting the Content-Type header to application/json. This informs the server that you’re sending JSON data and allows it to parse the data correctly. Without this header, the server might misinterpret the data, leading to errors or unexpected behavior.

Another essential option is CURLOPT_POSTFIELDS. This option allows you to specify the data to be sent in the POST request. In the case of JSON data, you need to encode your PHP array or object into a JSON string using the json_encode() function. This function converts your PHP data structure into a JSON string that can be sent over the network. It’s also important to set CURLOPT_RETURNTRANSFER to true to ensure that the cURL function returns the server’s response as a string, which you can then process in your PHP code. Setting this option to false means you will receive the response directly into the output buffer, which is not usually what you want when posting data programmatically.

Here’s a step-by-step breakdown of setting up the cURL options:

  1. Initialize the cURL session using curl_init().
  2. Set the CURLOPT_URL option to the target URL.
  3. Set CURLOPT_POST to true to indicate a POST request.
  4. Encode your PHP data into a JSON string using json_encode().
  5. Set CURLOPT_POSTFIELDS to the JSON string.
  6. Set the Content-Type header to application/json using CURLOPT_HTTPHEADER.
  7. Set CURLOPT_RETURNTRANSFER to true to capture the response.

Here’s an example of the PHP code to set the necessary options:

$url = 'https://api.example.com/endpoint'; $data = array('name' => 'John Doe', 'email' => 'john.doe@example.com'); $json_data = json_encode($data); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

Executing the cURL Request and Handling Responses

Once you have configured the cURL options, the next step is to execute the request and handle the server’s response. This involves using the curl_exec() function to send the request and then processing the returned data. It’s crucial to check for errors during the cURL execution. The curl_errno() function returns an error number if an error occurred, and curl_error() returns a human-readable error message. Handling these errors gracefully is essential for ensuring the reliability of your application.

After executing the cURL request, you’ll receive a response from the server. This response typically includes a status code and a body containing data, often in JSON format. You can use the curl_getinfo() function to retrieve information about the request, such as the HTTP status code. A status code of 200 indicates success, while other codes, such as 400 (Bad Request) or 500 (Internal Server Error), indicate errors. If the response body contains JSON data, you can use the json_decode() function to convert it back into a PHP array or object.

This paragraph is optimized for featured snippets: To POST JSON data with PHP cURL, first encode your data into a JSON string using json_encode(). Then, initialize a cURL session, set the CURLOPT_URL to the API endpoint, CURLOPT_POST to true, and CURLOPT_POSTFIELDS to the JSON string. Crucially, set the Content-Type header to application/json to inform the server about the data format. Finally, execute the cURL request using curl_exec() and handle the response, checking for errors and decoding the returned JSON data with json_decode() if necessary.

Here’s an example of how to execute the cURL request and handle the response:

$response = curl_exec($ch); if (curl_errno($ch)) { echo 'cURL error: ' . curl_error($ch); } else { $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); echo "HTTP Code: " . $http_code . "\n"; if ($http_code == 200) { $data = json_decode($response, true); print_r($data); } else { echo "Error: " . $response; } } curl_close($ch); 

Best Practices and Security Considerations

When working with cURL and JSON data, it’s essential to follow best practices to ensure the security and reliability of your code. One crucial aspect is validating the data you’re sending and receiving. This helps prevent malicious data from being injected into your application. Always sanitize your input and output to mitigate risks like cross-site scripting (XSS) and SQL injection. You should also implement error handling to gracefully manage unexpected situations, such as network errors or invalid server responses.

Another important consideration is using HTTPS for all your API requests. HTTPS encrypts the data transmitted between your application and the server, protecting it from eavesdropping and tampering. You can enforce HTTPS by setting the CURLOPT_SSL_VERIFYPEER option to true and providing a valid certificate authority (CA) file. This ensures that your application only connects to servers with valid SSL certificates. It’s also wise to limit the amount of data you expose and to avoid storing sensitive information unnecessarily. According to OWASP, failure to properly validate input is a leading cause of web application vulnerabilities [2].

Here are some key security considerations:

  • Always use HTTPS to encrypt your data.
  • Validate and sanitize all input data.
  • Implement robust error handling.
Infographic here
Furthermore, consider using prepared statements or parameterized queries when interacting with databases to prevent SQL injection attacks. Regularly update your PHP installation and cURL library to patch security vulnerabilities. By following these best practices, you can significantly reduce the risk of security breaches and ensure the integrity of your application. You can find additional resources and security tips on the PHP documentation website \[3\].

FAQ: Posting JSON Data with PHP cURL

Q: Why is my POST request not working?
A: Double-check that you've set the Content-Type header to application/json and that you've correctly encoded your data into a JSON string using json\_encode(). Also, ensure that the target URL is correct and that the server is expecting a POST request.
Q: How do I handle different HTTP status codes?
A: Use curl\_getinfo() to retrieve the HTTP status code and then implement conditional logic to handle different codes, such as 200 (OK), 400 (Bad Request), 401 (Unauthorized), and 500 (Internal Server Error).
Q: Is it safe to disable SSL verification?
A: Disabling SSL verification (CURLOPT\_SSL\_VERIFYPEER to false) is generally not recommended as it can expose your application to man-in-the-middle attacks. Only disable it if you have a very specific reason and understand the risks involved.
- Ensure correct JSON encoding. - Properly handle HTTP status codes.

By understanding these common issues and their solutions, you can troubleshoot and resolve problems more effectively.

Mastering how to POST JSON data with PHP cURL is a vital skill for any web developer. This article provided a comprehensive guide, covering the fundamentals, setup, execution, and security considerations. By following the steps and best practices outlined here, you can confidently integrate your PHP applications with JSON-based APIs and services. Remember that continuous learning and experimentation are key to becoming proficient in this area. Now, take what you’ve learned and start building robust and interconnected applications! Explore related topics like API authentication, request throttling, and asynchronous request processing to further expand your knowledge and capabilities. Visit our website to learn more about PHP development and related technologies.

[1]: Statista Report - API Usage Statistics: Statista [2]: OWASP - Input Validation: OWASP [3]: PHP Documentation: PHP.net

Question & Answer :
Here is my code,

$url = 'url_to_post'; $data = array( "first_name" => "First name", "last_name" => "last name", "email"=>"<a class="__cf_email__" data-cfemail="bedbd3dfd7d2fed9d3dfd7d290ddd1d3" href="/cdn-cgi/l/email-protection">[email protected]</a>", "addresses" => array ( "address1" => "some address", "city" => "city", "country" => "CA", "first_name" => "Mother", "last_name" => "Lastnameson", "phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) ); $data_string = json_encode($data); $ch=curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, array("customer"=>$data_string)); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type:application/json', 'Content-Length: ' . strlen($data_string) ) ); $result = curl_exec($ch); curl_close($ch); 

And at other page, I am retrieving post data.

print_r ($_POST); 

Output is

HTTP/1.1 200 OK Date: Mon, 18 Jun 2012 07:58:11 GMT Server: Apache X-Powered-By: PHP/5.3.6 Vary: Accept-Encoding Connection: close Content-Type: text/html Array ( ) 

So, I am not getting proper data even at my own server, it’s empty array. I want to implement REST using json as at http://docs.shopify.com/api/customer#create

You are POSTing the json incorrectly – but even if it were correct, you would not be able to test using print_r($_POST) (read why here). Instead, on your second page, you can nab the incoming request using file_get_contents("php://input"), which will contain the POSTed json. To view the received data in a more readable format, try this:

echo ''.print_r(json_decode(file_get_contents("php://input")),1).''; 

In your code, you are indicating Content-Type:application/json, but you are not json-encoding all of the POST data – only the value of the “customer” POST field. Instead, do something like this:

$ch = curl_init( $url ); # Setup request to send json via POST. $payload = json_encode( array( "customer"=> $data ) ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload ); curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); # Return response instead of printing. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); # Send request. $result = curl_exec($ch); curl_close($ch); # Print response. echo "$result"; 

Sidenote: You might benefit from using a third-party library instead of interfacing with the Shopify API directly yourself.