2

How to send a redirect post request to external url? my code in controller:

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

4 Answers4

2

You can redirect your request using HTTP 301

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

Or use any php http clients like Guzzle (see How do I send a POST request with PHP?).

There is no other options.

Anton Rybalko
  • 1,229
  • 17
  • 23
  • 301 redirection will loose POST data - you definitely don't want to do this. – rob006 Jul 31 '18 at 13:36
  • You can send post data as get parameters. Or send post request via php http client. See https://stackoverflow.com/questions/2604530/a-good-way-to-redirect-with-a-post-request – Anton Rybalko Aug 01 '18 at 00:47
2

You need to use 307 status code to specify redirection which should be performed with the same POST data.

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

The HTTP 307 Temporary Redirect redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Locationheaders.

The method and the body of the original request are reused to perform the redirected request.

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

rob006
  • 21,383
  • 5
  • 53
  • 74
  • Hi Rob, thank you for this one. I can send my post request and gets redirected however the server isn't acknowledging my request, but when I use regular html form(not in yii2), it accepts my request. any thoughts on this? Cheers – Sean Aug 01 '18 at 05:13
0

Easily you can do it with Guzzle. From the documentation I think something like the below code is exactly what you want.

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'
            ]
        ]
    ]);
}
meysam
  • 1,754
  • 2
  • 20
  • 30
0

You can send data to the external server using CURL.

You can use the following code to send the post request to 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));
    }
akshaypjoshi
  • 1,245
  • 1
  • 15
  • 24