Але*_*кин 4 php post redirect curl
我有一个脚本将POST数据发送到几个页面.但是,我在向某些服务器发送请求时遇到了一些困难.原因是重定向.这是模型:
为了解决这个问题,我使用了curl_setopt($ ch,CURLOPT_CUSTOMREQUEST,"POST"),是的,现在它重定向没有我在第一次请求中发送的POST正文内容.如何在重定向时强制卷曲发送帖子正文?谢谢!
这是一个例子:
<?php
function curlPost($url, $postData = "")
{
$ch = curl_init () or exit ( "curl error: Can't init curl" );
$url = trim ( $url );
curl_setopt ( $ch, CURLOPT_URL, $url );
//curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postData );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 30 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30 );
curl_setopt ( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36");
curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, TRUE);
$response = curl_exec ( $ch );
if (! $response) {
echo "Curl errno: " . curl_errno ( $ch ) . " (" . $url . " postdata = $postData )\n";
echo "Curl error: " . curl_error ( $ch ) . " (" . $url . " postdata = $postData )\n";
$info = curl_getinfo($ch);
echo "HTTP code: ".$info["http_code"]."\n";
// exit();
}
curl_close ( $ch );
// echo $response;
return $response;
}
?>
Run Code Online (Sandbox Code Playgroud)
curl遵循RFC 7231建议的内容,这也是浏览器通常为301响应做的事情:
Note: For historical reasons, a user agent MAY change the request
method from POST to GET for the subsequent request. If this
behavior is undesired, the 307 (Temporary Redirect) status code
can be used instead.
Run Code Online (Sandbox Code Playgroud)
如果您认为这是不受欢迎的,您可以使用该CURLOPT_POSTREDIR选项进行更改,该选项在PHP中似乎只是非常稀疏地记录,但是libcurl文档解释了它.通过在那里设置正确的位掩码,然后在重定向后进行curl not change方法.
如果您为此控制服务器端,则更容易的修复是确保返回307响应代码而不是301.