如何在 PHP CURL 中从 POST 切换到 GET

我已经尝试从以前的 Post 请求切换到 Get 请求。它假设它是一个 Get,但是最终会发布一个帖子。

我在 PHP 中尝试了以下方法:

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

我错过了什么?

附加信息: 我已经建立了一个连接来执行 POST 请求。这个过程成功地完成了,但是后来当我尝试重用连接并使用上面的 setopts 切换回 GET 时,它仍然会在内部执行一个 POST,其中包含不完整的 POST 头。问题在于,它认为自己在执行 GET 操作,但最终放置了一个没有 content-length 参数的 POST 头,并且连接失败,出现了411个错误。

272621 次浏览

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.

Solved: The problem lies here:

I set POST via both _CUSTOMREQUEST and _POST and the _CUSTOMREQUEST persisted as POST while _POST switched to _HTTPGET. The Server assumed the header from _CUSTOMREQUEST to be the right one and came back with a 411.

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');

Add this before calling curl_exec($curl_handle)

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');

CURL request by default is GET, you don't have to set any options to make a GET CURL request.

add this based on a condition. Code with this line is a POST request and otherwise It will be GET by default. Also We can add the parameters at the end of the URL even if it is POST request

curl_setopt($curl_handle, CURLOPT_POST, 1);