Home >Backend Development >PHP Tutorial >How Can I Use cURL in PHP to Send JSON Data for PUT, POST, GET, and DELETE Requests?

How Can I Use cURL in PHP to Send JSON Data for PUT, POST, GET, and DELETE Requests?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 08:23:10118browse

How Can I Use cURL in PHP to Send JSON Data for PUT, POST, GET, and DELETE Requests?

Passing JSON through Curl in PHP for PUT, POST, GET

When working with REST APIs, passing JSON data through curl is crucial for CRUD operations (Create, Read, Update, Delete). This article addresses this need by presenting PHP implementations for making PUT, POST, GET, and DELETE requests with JSON bodies.

PUT Request

$data = array('username' => 'dog', 'password' => 'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('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);

POST Request

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('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);

GET Request

$url .= '?' . http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

DELETE Request

$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 Can I Use cURL in PHP to Send JSON Data for PUT, POST, GET, and DELETE Requests?. 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