【问题标题】:Yii2 how to send form request to external urlYii2如何将表单请求发送到外部url
【发布时间】:2019-01-04 21:05:53
【问题描述】:

如何将重定向发布请求发送到外部 url?我在控制器中的代码:

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
      // send post request to external link
    }

【问题讨论】:

  • 答案是:你不能。您可以在会话中保存变量或构建 html 表单并通过 JavaScript 自动提交。
  • 为什么要这样做?
  • @AntonRybalko 嗨,因为我想重定向到托管页面(这是一个外部链接),它需要通过 http post request form 重定向发送参数。
  • 我不能在这个上使用 curl,因为它需要重定向。

标签: php post yii2


【解决方案1】:

您可以使用 HTTP 301 重定向您的请求

Yii::$app->response->redirect('url', 301);
Yii::$app->end();

或使用任何 php http 客户端,例如 Guzzle(请参阅 How do I send a POST request with PHP?)。

没有其他选择。

【讨论】:

  • 301 重定向会丢失 POST 数据 - 你绝对不想这样做。
  • 您可以将post数据作为get参数发送。或者通过 php http 客户端发送 post 请求。见stackoverflow.com/questions/2604530/…
【解决方案2】:

您需要使用307 状态码来指定应该使用相同的 POST 数据执行的重定向。

$this->redirect('https://example.com', 307);

HTTP 307 Temporary Redirect 重定向状态响应代码表示请求的资源已临时移动到Locationheaders 给出的 URL。

重用原始请求的方法和正文来执行重定向请求。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307

【讨论】:

  • 嗨,Rob,谢谢你。我可以发送我的帖子请求并被重定向,但是服务器没有确认我的请求,但是当我使用常规的 html 表单(不在 yii2 中)时,它会接受我的请求。对此有什么想法吗?干杯
【解决方案3】:

您可以使用Guzzle 轻松做到这一点。来自the documentation,我认为下面的代码正是您想要的。

if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    $response = $client->request('POST', 'http://httpbin.org/post', [
        'form_params' => [
            'field_name' => 'abc',
            'other_field' => '123',
            'nested_field' => [
                'nested' => 'hello'
            ]
        ]
    ]);
}

【讨论】:

    【解决方案4】:

    您可以使用 CURL 将数据发送到外部服务器。

    您可以使用以下代码将 post 请求发送到 URL。

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $url = 'http://www.example-redirect.com';
            $host = "http://www.example.com";
            $postData = Yii::$app->request->post();
    
            $ch = curl_init($host);
            $data = http_build_query($postData);
    
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);
            // Redirect from here
            return $this->redirect(Url::to($url));
        }
    

    【讨论】:

    • 嗨,谢谢,但它需要重定向到托管页面。
    • 对于重定向,您可以使用 Url Helper。 return $this->redirect(Url::to('https://www.example.com'));
    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多