When working with APIs, it’s common to send and receive data in JSON format. In PHP, you can use the cURL library to send HTTP requests, including sending JSON data in a POST request. In this article, we’ll show you how to POST JSON data with PHP cURL in a step-by-step guide.
Step 1: Set the URL and JSON data
The first step is to set the URL that you want to send the request to and the JSON data that you want to send in the request body. For this example, we’ll use a sample JSON data:
1 2 3 4 5 6 7 | $data = array( 'name' => 'John Doe', 'phone' => '1234567890' ); $json = json_encode($data); |
In this example, we’ve created an array of data and encoded it into a JSON string using the json_encode()
function.
Step 2: Set the cURL options
The next step is to set the cURL options for the request, including the URL, request method, and request body. Here’s an example of how to set the cURL options:
1 2 3 4 5 6 7 8 9 10 | $url = 'https://example.com/api/create'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($json) )); |
In this example, we’ve set the following options:
- CURLOPT_RETURNTRANSFER: Set to true to return the response as a string instead of outputting it directly to the screen.
- CURLOPT_CUSTOMREQUEST: Set to “POST” to specify that we’re sending a POST request.
- CURLOPT_POSTFIELDS: Set to the JSON data that we want to send in the request body.
- CURLOPT_HTTPHEADER: Set to an array of headers, including the Content-Type header to specify that we’re 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
The final step is to send the request using the curl_exec()
function and handle the response. Here’s an example of how to do this:
1 2 3 4 5 6 7 | $response = curl_exec($ch); if(curl_errno($ch)) { echo 'Error: ' . curl_error($ch); } else { echo $response; } curl_close($ch); |
In this example, we’ve used the curl_exec()
function to send the request and store the response in the $response variable. We’ve also checked for any errors using the curl_errno()
function and displayed the error message if there was an error. Finally, we’ve closed the cURL handle using the curl_close()
function.
Step 4: Complete PHP Script
After combining the above code, you will get a full functional PHP script that can POST JSON data to remote APIs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?php $data = array( 'name' => 'John Doe', 'phone' => '1234567890' ); $json = json_encode($data); $url = 'https://example.com/api/create'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($json) )); $response = curl_exec($ch); if(curl_errno($ch)) { echo 'Error: ' . curl_error($ch); } else { echo $response; } curl_close($ch); ?> |
Save the file content and run this via the PHP command line interface.
Conclusion
In this article, we’ve shown you how to POST JSON data with PHP cURL in a step-by-step guide. By setting the URL and JSON data, setting the cURL options, and sending the request, and handling the response, you can easily send JSON data in a POST request using PHP cURL.
13 Comments
## Hello everyone, I have a problem I am developing a data submission using the following code i get a:
Error: Failed to connect to 54.193.100.127 port 5175 after 0 ms: Couldn’t connect to server
‘100000000000001’,
‘lattitude’ => ‘17.983601’,
‘longitude’ => ‘-102.357148’,
‘speed’ => ‘0’,
‘angle’ => ‘0’,
‘satellite’ => ‘8’,
‘time’ => ‘2023-06-07 05:56:00’,
‘battery_voltage’ => ’20’,
‘gps_validity’ => ‘A’
);
$json = json_encode($datos);
echo $json; echo “”;
echo strlen($json); echo “”;
//$url = ‘http://54.193.100.127:5175’; //add curlopt_port
$url = ‘http://54.193.100.127’;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PORT, 5175);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, “POST”);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
‘Content-Type: application/json’,
‘Content-Length: ‘ . strlen($json)
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$response = curl_exec($ch);
if(curl_errno($ch)) {
echo ‘Error: ‘ . curl_error($ch);
} else {
echo ‘Respuesta: ‘; echo $response;
}
?>
// But when I use the terminal with the curl command as follows:
curl -X POST -d ‘{“imei_no”:”861172035412985″,”lattitude”:”17.983601″,”longitude”:”-102.357148″,”speed”:”0″,”angle”:”0″,”satellite”:”8″,”time”:”2023-06-07 05:56:00″,”battery_voltage”:”20″,”gps_validity”:”A”}’ -H “Content-Type: application/json” http://54.193.100.127:5175
//The server responds
{“status”:”true”}
Can you help me?
nice This was very helpful! Thanks for posting!
The main thing is that the request must be a POST request with properly json-encoded data in the body. The headers must properly describe the post body.
very helpful,
thank you
Is there a way to avoid the auto “Content-Type: application/x-www-form-urlencoded
” when using POST, I mean, I’m using the following code:
//—————————————————————————————————-
$ch = curl_init();
if(!empty($gdxParams))
{
$curlUrl=$curlUrl.’?’.$gdxParams;
}
$curlOptions=array();
if($gdxMethod==”POST”)
{
$curlOptions=[
CURLOPT_HTTPHEADER=>[
‘x-api-key: ‘.$gdxApiKey,
‘Authorization: Bearer ‘.$gdxApiKey,
‘Content-Type: application/json’,
],
CURLOPT_URL=>$curlUrl,
CURLOPT_CUSTOMREQUEST=>’POST’,
CURLOPT_POSTFIELDS=>json_encode($gdxArrayParams),
CURLOPT_RETURNTRANSFER=>true,
CURLINFO_HEADER_OUT=>true,
];
}
else//Method GET
{
$curlOptions=[
CURLOPT_HTTPHEADER=>[
‘x-api-key: ‘.$gdxApiKey,
‘Authorization: Bearer ‘.$gdxApiKey,
],
CURLOPT_URL=>$curlUrl,
CURLOPT_CUSTOMREQUEST=>’GET’,
CURLOPT_RETURNTRANSFER=>true,
CURLINFO_HEADER_OUT=>true,
];
}
curl_setopt_array($ch, $curlOptions);
$response = curl_exec($ch);
/*—*/
$arrayInfo=array();
$arrayInfo[‘header_info’]=curl_getinfo($ch, CURLINFO_HEADER_OUT);
$arrayInfo[‘response’]=$response;
var_dump($arrayInfo);
/*—*/
//————————————————————————————————
But the header info always gets set as:
//—————————————————————————————————————
‘header_info’ => string ‘POST /v1/reservations?tripId=XXXXXXXXXXXXXXXXXX&lang=es&verifyDuplicatedReservations=true HTTP/1.1
Host: stage.ws.gdx.travel
Accept: */*
x-api-key: XXXXXXXXXXXXXXXXXXXXXX
Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXX
Content-Type: application/json
Content-Length: 221
Content-Type: application/x-www-form-urlencoded
//——————————————————————————————————
If I remove the CURLOPT_POSTFIELDS option, the headers only gets one “Content-Type” line (application/json, the one that I need)
Any clues?
it doesn´t work … boolean false is returned, while it works using Postman client
How to make a get request to the api using cURL
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
‘Content-Type: application/json’,
‘Content-Length: ‘ . strlen($payload))
);
You are asking for strlen($payload); which is the string-length while $payload is an array, so that gives an error?
Any advise?
IHAB,
json_encode turns the array into a JSON string, so strlen() will work.
Thanks a lot
This was very helpful! Thanks for posting!
Your all tutorilas are awesome bro. Plese provide some a big project in Core Php or CI .
How about radio buttons or select option?