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:

curl -X PUT -H "Content-Type: application/json" -d 'json_object' http://example.com/resource

To pass a JSON object through cURL using the POST method, you can use the following command:

curl -X POST -H "Content-Type: application/json" -d 'json_object' http://example.com/resource

To pass a JSON object through cURL using the GET method, you can use the following command:

curl -X GET -H "Content-Type: application/json" -d 'json_object' http://example.com/resource

Watch a course Learn object oriented PHP

In PHP you can use the curl_setopt() function to set the HTTP method and the data to be sent as JSON.

<?php

$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);

You can change the method to POST or GET and the json_encode to match the json_object you want to send.