Yii returnUrl函数

时间:2012-03-10 14:31:17

标签: php redirect frameworks login yii

大家好,我在main.php配置文件中有这段代码:

'components' => array(
    '[.........]',
    'user'=>array(
        // enable cookie-based authentication
        'allowAutoLogin'=>true,
        'autoRenewCookie' => true,
        'returnUrl' => 'http://stackoverflow.com',
    )
);

我的问题是,ID在登录后没有将用户重定向到http://stackoverflow.com,你能帮我吗?

UserController.php:

public function actionLogin()
{
    if (!Yii::app()->user->isGuest){
        $this->redirect('/user/index');
        return;
    }

    $model=new LoginForm;

    // if it is ajax validation request
    if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }

    // collect user input data
    if(isset($_POST['LoginForm']))
    {
        $model->attributes=$_POST['LoginForm'];
        // validate user input and redirect to the previous page if valid
        if($model->validate() && $model->login())
            $this->redirect(Yii::app()->user->returnUrl);
    }
    // display the login form
    $this->render('login',array('model'=>$model));
}

3 个答案:

答案 0 :(得分:8)

我找到了解决问题的方法。我在login.php中添加了这行代码,因此在用户登录后,它将重定向到上一页:

if (Yii::app()->request->urlReferrer != 'http://www.example.com/user/login' && 
    Yii::app()->request->urlReferrer != 'http://www.example.com/user/register')
{
    Yii::app()->user->setReturnUrl(Yii::app()->request->urlReferrer);
}

答案 1 :(得分:1)

尝试此操作以跟踪上次访问的有效网址:

添加到您的配置:

'preload' => array(
    // preloading 'loginReturnUrlTracker' component to track the current return url that users should be redirected to after login
    'loginReturnUrlTracker'
),
'components' => array(
    'loginReturnUrlTracker' => array(
        'class' => 'application.components.LoginReturnUrlTracker',
    ),
    ...
),

将此文件放在components / LoginReturnUrlTracker.php中:

<?php

class LoginReturnUrlTracker extends CApplicationComponent
{

    public function init()
    {
        parent::init();

        $action = Yii::app()->getUrlManager()->parseUrl(Yii::app()->getRequest());

        // Certain actions should not be returned to after login
        if ($action == "site/error") {
            return true;
        }
        if ($action == "site/logout") {
            return true;
        }
        if ($action == "site/login") {
            return true;
        }

        // Keep track of the most recently visited valid url
        Yii::app()->user->returnUrl = Yii::app()->request->url;

    }

}

答案 2 :(得分:0)

Yii会覆盖在配置文件中设置的返回URL。

您可以在参数中定义此返回网址,也可以通过createUrl函数生成此链接。