How to validate session with Angularjs and PHP?

Asked

Viewed 893 times

0

After the login is done, how can I validate the user when it goes from one page to another, within the system, using Angularjs and PHP? Because when I worked, only with html and php I did it this way:

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

if ($usuario == ""){
   header("Location:index.php");
}
?>

1 answer

2

Assuming you are consuming something in ajax to the templates of an API for example, after logging in, any ajax page that you want to access on the server must have some sort of verification if the user is logged in.

Step 1

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

Step 2

EVERY page returned to the user must contain a checker, which can be a 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 return, check if it does not contain the variable logado with value of 0, and if so, abort the current operation and forward the user to the login screen 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 well your doubts, then just go improving the code to adapt to your reality.

  • I’ll try. .

  • Either way works. The important thing is to register the session

  • No, I was stating that I still have to create the part that logs into the system.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.