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

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

DDD
DDDOriginal
2024-12-20 07:38:17687browse

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

cURL in PHP: Passing JSON Data via PUT, POST, GET

In REST API development, cURL is a valuable tool for testing and communicating with remote servers. This article demonstrates how to pass JSON data through cURL using four common HTTP methods: PUT, POST, GET, and DELETE.

PUT

This method allows you to update a resource. The following PHP code sample shows how to send JSON data in a PUT request:

<?php
$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

POST is used to create a new resource. The PHP code below showcases how to send JSON data with a POST request:

<?php
$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

GET is designed to retrieve resources. Since JSON data cannot be appended to a URL, you must encode it and pass it as a query string parameter. Refer to @Dan H's answer for a working example of sending JSON data with a GET request.

DELETE

The DELETE method removes a resource from the server. The following PHP code demonstrates how to perform a DELETE operation with JSON data:

<?php
$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 PUT, POST, GET, 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