Curl and PHP - how can I pass a json through curl by PUT,POST,GET
To pass a JSON object through cURL using the PUT method, you can use the following command:
To pass a JSON object through cURL using the PUT method, you can use the following shell command:
Example of passing a JSON object through cURL using the PUT method (CLI)
curl -X PUT -H "Content-Type: application/json" -d '{"key":"value"}' http://example.com/resourceTo pass a JSON object through cURL using the POST method, you can use the following shell command:
Example of passing a JSON object through cURL using the POST method (CLI)
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' http://example.com/resourceTo pass a JSON object through cURL using the GET method, note that GET requests typically do not include a request body:
Example of passing a JSON object through cURL using the GET method (CLI)
curl -X GET http://example.com/resource
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
In PHP you can use the curl_setopt() function to set the HTTP method and the data to be sent as JSON.
Example of using the curl_setopt() function to set the HTTP method and the data to be sent as JSON in PHP
<?php
$data = ['key' => 'value'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/resource");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: ' . strlen(json_encode($data))]);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);You can change the method to POST or GET. Note that for GET requests in PHP, you should remove CURLOPT_POSTFIELDS and the Content-Length header, as GET requests do not send a request body.