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
Release: 2024-12-02 08:23:10
Original
110 people have browsed it

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);
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template