Home >Backend Development >PHP Tutorial >How to Send JSON Data with cURL in PHP using GET, POST, PUT, and DELETE?

How to Send JSON Data with cURL in PHP using GET, POST, PUT, and DELETE?

Barbara Streisand
Barbara StreisandOriginal
2024-11-29 21:57:11198browse

How to Send JSON Data with cURL in PHP using GET, POST, PUT, and DELETE?

Sending JSON Data with Curl in PHP: GET, PUT, POST, and DELETE

Introduction

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.

Passing JSON through PUT

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

Passing JSON through POST

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

Passing JSON through GET

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.

Passing JSON through DELETE

$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn