带有 Curl : follow redirect with POST 的 PHP

标签 php redirect post curl

我有一个脚本可以将 POST 数据发送到多个页面。但是,我在向某些服务器发送请求时遇到了一些困难。原因是重定向。这是模型:

  1. 我正在向服务器发送 post 请求
  2. 服务器响应:301 永久移动
  3. 然后 curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, TRUE) 启动并遵循重定向(但通过 GET 请求)。

为了解决这个问题,我正在使用 curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST") 是的,现在它的重定向没有我在第一个请求中发送的 POST 正文内容。如何强制 curl 在重定向时发送帖子正文?谢谢!

例子如下:

<?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;
}
?>

最佳答案

curl 在跟踪什么 RFC 7231 suggests ,这也是浏览器通常对 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.

如果您认为这是不可取的,您可以使用 CURLOPT_POSTREDIR 选项更改它,该选项在 PHP 中似乎只有很少的文档,但是 the libcurl docs explains it .通过在此处设置正确的位掩码,您可以让 curl 在重定向后更改方法。

如果您为此控制服务器端,更简单的解决方法是确保返回 307 响应代码而不是 301。

关于带有 Curl : follow redirect with POST 的 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359720/

相关文章:

ruby-on-rails - rails + Angular : Redirection After Sign-In/Up

php - 将通过 POST Http 请求(okhttp 3.3.1)上传的多个文件移动到另一个目录

c# - 如何检测 Console.In (stdin) 是否被重定向?

ruby-on-rails - 登录后 Rails 设计重定向

java - 使用 HttpURLConnection 发送二进制数据

php - 我正在开发一个将信息提交到数据库的 AJAX 表单。当到达插入函数时它会记录错误

使用 magento/bin 设置 :di:compile 在 docker 中耗尽 PHP 内存大小

php - PDO 绑定(bind)参数

php - 使用 AJAX 执行 PHP 脚本而不使用 POST/GET?

php - Google PlayIntegrity API - 通过 PHP 验证 token