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

How to Send JSON Data with Curl and PHP using PUT, POST, and GET?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 06:03:13775browse

How to Send JSON Data with Curl and PHP using PUT, POST, and GET?

Curl and PHP: Passing JSON Data via PUT, POST, and GET

When using curl in PHP to interact with a REST API, JSON data can be transmitted through three common HTTP request methods: PUT, POST, and GET. This article provides a detailed guide on how to achieve these data transfers effectively.

PUT

To perform a PUT request with a JSON payload, follow these steps:

$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

For a POST request with JSON data, use this code:

$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

As outlined in @Dan H's response, you can incorporate JSON data into a GET request by appending it to the URL as a query string:

$url .= '?data=' . urlencode(json_encode($data));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
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 and PHP using PUT, POST, and GET?. 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