YII2 post logout link on non YII2 page
I've created a YII2 site I want to allow the user to logout, not on a page in the YII2 folder. In YII2 I'm using the nav component, so the logout part of the layout looks like this
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right player-page'],
'encodeLabels' => false,
'items' => [
[
'label' => 'Logout',
'items' => [
[
'label' => 'Sign out (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'template' => '<a href="{url}" data-method="post">{label}</a>',
'linkOptions' => ['data-method' => 'post']
],
],
],
],
]);
I've tried Javascript. This is the latest one.
window.onload=function() {
document.getElementById("logout").onclick=function() {
var myForm = document.createElement("form");
myForm.action='http://151.236.49.237/~aceify1/booking/site/logout';// the href of the link
myForm.target="myFrame";
myForm.method="POST";
document.body.appendChild(myForm);
myForm.submit();
return false; // cancel the actual link
}
}
But it just says internal server error on the YII2 logout URL.
Any ideas would be much appreciated.
1 answer
-
answered 2019-11-14 14:43
disembarkedone
You can disable the CSRF validation check for the logout function. Add this to your controller, or modify your already existing beforeAction() as required
public function beforeAction($action) { if ($action->id == 'logout') { $this->enableCsrfValidation = false; } return parent::beforeAction($action); }