Home >Backend Development >PHP Tutorial >How to Send JSON Data with cURL in PHP using GET, POST, PUT, and DELETE?
Curl is a versatile tool for making HTTP requests and working with web APIs. In PHP, you can leverage Curl to pass JSON data through various HTTP methods like PUT, POST, GET, and DELETE.
$data = ['username' => 'dog', 'password' => 'tall']; $data_json = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: ' . strlen($data_json)]); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
As mentioned in the question, adding JSON data to a GET request is not typically done in the URL. This is because GET requests are traditionally used to fetch resources without modifying them.
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
The above is the detailed content of How to Send JSON Data with cURL in PHP using GET, POST, PUT, and DELETE?. For more information, please follow other related articles on the PHP Chinese website!