Reputation: 61
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
}
Upvotes: 2
Views: 3663
Reputation: 1295
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));
}
Upvotes: 0
Reputation: 22174
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 theLocation
headers.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
Upvotes: 2
Reputation: 1314
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.
Upvotes: 2
Reputation: 1794
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'
]
]
]);
}
Upvotes: 0