Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch from POST to GET in PHP CURL

Tags:

post

php

curl

get

I have tried switching from a previous Post request to a Get request. Which assumes its a Get but eventually does a post.

I tried the following in PHP :

curl_setopt($curl_handle, CURLOPT_POSTFIELDS, null); curl_setopt($curl_handle, CURLOPT_POST, FALSE); curl_setopt($curl_handle, CURLOPT_HTTPGET, TRUE); 

What am I missing?

Additional information: I already have a connection that's setup to do a POST request. That completes successfully but later on when I try to reuse the connection and switch back to GET using the setopts above it still ends up doing a POST internally with incomplete POST headers. The problem is it believes its doing a GET but ends up putting a POST header without the content-length parameter and the connection fails witha 411 ERROR.

like image 894
gnosio Avatar asked Aug 04 '09 01:08

gnosio


People also ask

What is Curlopt_returntransfer in cURL?

CURLOPT_RETURNTRANSFER: Converts output to a string rather than directly to the screen. CURLOPT_HTTPHEADER: Request header information with an array of parameters, as shown in the example of "Browser-based redirection"

What is Curl_setopt?

The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option.


1 Answers

Make sure that you're putting your query string at the end of your URL when doing a GET request.

$qry_str = "?x=10&y=20"; $ch = curl_init();  // Set query data here with the URL curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php' . $qry_str);   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 3); $content = trim(curl_exec($ch)); curl_close($ch); print $content; 

With a POST you pass the data via the CURLOPT_POSTFIELDS option instead of passing it in the CURLOPT__URL.

$qry_str = "x=10&y=20"; curl_setopt($ch, CURLOPT_URL, 'http://example.com/test.php');   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 3);  // Set request method to POST curl_setopt($ch, CURLOPT_POST, 1);  // Set query data here with CURLOPT_POSTFIELDS curl_setopt($ch, CURLOPT_POSTFIELDS, $qry_str);  $content = trim(curl_exec($ch)); curl_close($ch); print $content; 

Note from the curl_setopt() docs for CURLOPT_HTTPGET (emphasis added):

[Set CURLOPT_HTTPGET equal to] TRUE to reset the HTTP request method to GET.
Since GET is the default, this is only necessary if the request method has been changed.

like image 161
RC. Avatar answered Sep 19 '22 09:09

RC.