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.
The following example makes an HTTP POST request and send the JSON data to URL with cURL in PHP.
$url
) where the JSON data to be sent.application/json
using the CURLOPT_HTTPHEADER option.// 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($ch, CURLOPT_POSTFIELDS, $payload);
// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the POST request
$result = curl_exec($ch);
// Close cURL resource
curl_close($ch);
The following example shows how you can get or fetch the JSON POST data using PHP.
$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
Thank you very much!
P. s. “user” and $payload are not require. You can just write:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
//The data you want to send via POST
$payload = json_encode($message);
This is unnecessary. You can post a straight out JSON formatted string and it should work as expected.
This is a very useful article for all HPP developers.
Hi i not understand this point:
$payload = json_encode(array(“user” => $data));
what is user? is a name for array data?
Thank you so much. Finally getting a response has made my day
Perfect! Thank very mush.
It’s really helpful
what about sending a GET request with a json data ?
Short and sweet. Thank you for the post, this helped me get up and running quickly
Great !!!
Thank you
Thank you! Very helpful!
Its very helpful for me Thank you!
how we can send and receive a file?
It was helpful, thankss!!