How to validate session with AngularJS and PHP?

0

Once the login is done, how can I validate the user when it goes from one page to another, inside the system, using AngularJS and PHP? Well, when I worked with just html and php I did the following:

<?php
session_start();
$id_usuario = $_SESSION['id_usuario'];
$usuario = $_SESSION['user'];

if ($usuario == ""){
   header("Location:index.php");
}
?>
    
asked by anonymous 12.11.2015 / 03:25

1 answer

2

Assuming that you are consuming something in ajax to the molds of an API for example, after login, any page in ajax that you want to access on the server should have some kind of verification if the user is logged in.

Step 1

On your login page you activate a session variable called $_SESSION['usuarioLogado'] = 1; for example.

Step 2

Any page returned to the user must contain a checker, which can be an include with the following code:

<?php
if($_SESSION['usuarioLogado'] != 1){
    $status = array('logado' => 0);
    echo json_encode($status);
    exit();
}
?>

Step 3

In your angular script you need, before using the server's return, to check that it does not contain the logado variable with the value of 0 , and if it does, abort the current operation and forward the user to the screen login again.

$http.get("arquivo-com-valores.php").success(function(data){
    $scope.retorno = data;

    //verifica se está logado
    if(angular.isDefined($scope.retorno.logado) && $scope.retorno.logado == 0){
        alert('Não está logado');
        document.location.href = "login.html";
    }

    //Continua com seu código normalmente...

});

With this will clarify your doubts well, then just go improving the code to adapt to your reality.

    
14.11.2015 / 13:07