Yii Session Not Working With Crossdomain Ajax

I’m using Yii in a web app and I’m having a problem using session.

I have two actions, actionLogin and actionGetUser. These methods are requested via a cross domain AJAX.

The session variable "id_usuario" is being set to the session in the actionLogin method (I used var_dump to make sure), but when I try to access it in the actionGetUsuario it is not set (isset returns false).

But the application works fine on the localhost (ajax requester is on the same domain), this problem only occurs in the online server.

I’ve tried changing the session_save_path, that’s not the problem (I think).

I’ve debugged it A LOT!

I found out that the session ID is being renewed every time the application makes a request.

Here are the two methods:

actionLogin:


public function actionLogin(){

    $model = new FormLogin();

    if(isset($_POST['email'])){

        $model->attributes = $_POST;

        if($model->validate()){

            $criteria = new CDbCriteria();

            $criteria->condition = 'email = :email AND senha = MD5(:senha)';

            $criteria->params = array(':email' => $model->email, ':senha' => $model->senha);

            if($usuario = Usuario::model()->find($criteria)){

                echo 'Login OK.';

                Yii::app()->session['id_usuario'] = $usuario->id_usuario;

            }else{

                Yii::app()->user->setFlash('loginFail', 'Email ou senha incorretos.');

                Yii::app()->session->remove('id_usuario');

                echo "Login FAIL.";

            }

        }else{

            foreach ($model->getErrors() as $key => $value) {

                Yii::app()->user->setFlash($key, $value);

            }

            echo "Login FAIL.";

        }

    }


}

actionGetUsuario:


public function actionGetUsuario(){

    //var_dump($_SESSION);

    if(isset(Yii::app()->session['id_usuario'])){

        $usuario = Usuario::model()->findByPk(Yii::app()->session['id_usuario']);

        if($usuario != NULL){

            $retorno = array(

            'nome' => $usuario->nome,

            'email' => $usuario->email,

            );


            echo json_encode($retorno);

            exit;

        }

    }

    echo '{"nome": null,"email": null}';

}

This is the AJAX code:


this.getUsuario = function() {

    objeto.usuario = null;

    $.ajax({

        dataType : "json",

        url : server + 'usuario/getusuario',

        async : false,

        success : function(data) {

            if(data.nome != null){

                objeto.usuario = data;

                console.log("Dados do usuario recebidos com sucesso.");

            }else{

                objeto.usuario = null;

                console.log("Usuário não encontrado ou não logado.");

                objeto.exibeFormularioLogin();

            }

        },

        error : function(e, tipo, msg) {

            console.log("Erro ao receber dados do usuario.\nMensagem de erro: " + msg);

            objeto.erro(e, msg);

        }

    });

    if (objeto.usuario == null)

        return false;

    else

        return true;

};

Can anyone help? :(

I’m not sure if this is your case, but many browsers reject 3rd party cookies.

May be… I’ve read that Yii or PHP uses a cookie to store the session ID. So, once the cookie is not being set, that might be causing this problem.

I have read a comment somewhere in Yii codebase, that cross domain ajax is not allowed. I cannot seem to find where i saw that. However, see if this thread helps: