Tags
Asked 2 years ago
9 Jun 2021
Views 201
QuickIos

QuickIos posted

How to switch from POST to GET in PHP CURL ?

How to switch from POST to GET in PHP CURL ?
web-api

web-api
answered Apr 26 '23 00:00

In PHP cURL, you can switch from using the POST method to using the GET method by setting the CURLOPT_HTTPGET option to true . Here's an example:



$url = 'http://example.com/api';
$data = array('param1' => 'value1', 'param2' => 'value2');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPGET, true); // set GET method
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // set POST data (ignored when using GET method)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return response as string
$response = curl_exec($ch);
curl_close($ch);

echo $response;

In this example, the CURLOPT_HTTPGET option is set to true to use the GET method instead of the default POST method. The CURLOPT_POSTFIELDS option is still set to the POST data, but it will be ignored when using the GET method.

Note that when using the GET method, the data is typically sent as URL parameters, rather than in the request body. In this example, the $ data array is not used when making the request with the GET method, but you can modify the URL to include the parameters as query string parameters, like this:



$url = 'http://example.com/api?' . http_build_query($data);

This will create a URL like http://example.com/api?param1=value1&param2=value2 , which includes the parameters as query string parameters. When using the GET method, these parameters will be included in the URL, rather than in the request body.
Post Answer