How to POST and Receive JSON Data using PHP cURL

JSON is the most popular data format for exchanging data between a browser and a server. The JSON data format is mostly used in web services to interchange data through API. When you working with web services and APIs, sending JSON data via POST request is the most required functionality. PHP cURL makes it easy to POST JSON data to URL. In this tutorial, we will show you how to POST JSON data using PHP cURL and get JSON data in PHP.

Send JSON data via POST with PHP cURL

The following example makes an HTTP POST request and send the JSON data to URL with cURL in PHP.

  • Specify the URL ($url) where the JSON data to be sent.
  • Initiate new cURL resource using curl_init().
  • Setup data in PHP array and encode into a JSON string using json_encode().
  • Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option.
  • Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.
  • Return the response as a string instead of outputting it using the CURLOPT_RETURNTRANSFER option.
  • Finally, the curl_exec() function is used to execute the POST request.
// API URL
$url 'https://www.example.com/api';

// Create a new cURL resource
$ch curl_init($url);

// Setup request to send json via POST
$data = array(
    
'username' => 'codexworld',
    
'password' => '123456'
);
$payload json_encode(array("user" => $data));

// Attach encoded JSON string to the POST fields
curl_setopt($chCURLOPT_POSTFIELDS$payload);

// Set the content type to application/json
curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type:application/json'));

// Return response instead of outputting
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);

// Execute the POST request
$result curl_exec($ch);

// Close cURL resource
curl_close($ch);

Receive JSON POST Data using PHP

The following example shows how you can get or fetch the JSON POST data using PHP.

  • Use json_decode() function to decoded JSON data in PHP.
  • The file_get_contents() function is used to receive data in a more readable format.
$data json_decode(file_get_contents('php://input'), true);

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

15 Comments

  1. VladAst Said...
  2. Valentin Secades Said...
  3. Harshana Malshan Said...
  4. Marco Said...
  5. Tracy Said...
  6. Marcelo Said...
  7. Saad Said...
  8. Mohamed Amine Modni Said...
  9. Chuck Said...
  10. Mateus Said...
  11. George K Said...
  12. Rustem Zakiev Said...
  13. Harpreet Kaur Said...
  14. Amir Said...
  15. Swati Said...

Leave a reply

keyboard_double_arrow_up