Search code examples
phphttp-redirecthyperlinkyii2

Yii redirecting to the link previously entered


im using yii2, and imagine for example an user types the url they want to go in like : http://webpage/user/example, if they are already logged in, there is no problem, it will open the right page. My problem is when the user is not logged in, so when he types that url, he is redirected to the login page(no problem so far, that is what is supposed to happen), but what i want to do is that after that user loggs in, he is redirected to the page he initially writed (http://webpage/user/example), so my problem is how to get if possible that url that was initially requested. Dont know if its even possible, but maybe you guys can help me!. Sorry about my english if there is any mistakes, thanks!


Solution

  • In controllers who actions needs to be logged, add this:

    public function beforeAction($action){
        if ($action->id != 'login') {
            Yii::$app->session->set("backURL", \Yii::$app->request->url, '/');
        }
        return parent::beforeAction($action);
    }
    

    After that your login action would be something like this:

    public function actionLogin() {
    
        if(!\Yii::$app->session->has("backURL")){
            Yii::$app->session->set("backURL", Yii::$app->request->referrer);
        }
    
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post())) {
            if($model->login()){
                return $this->redirect(\Yii::$app->session['backURL']);
            }
        } 
    
        return $this->render('/user/login', [
            'model' => $model,
        ]);
    }