Login system back to previous page in php

Asked

Viewed 2,256 times

4

I would like to make a system that the user when trying to access a url that needs to be logged in the script checks if it returns false it redirects to the login page and after logging in it automatically returns to the url that he was trying to access, how can I do this in php?

  • Voce could make a login system via modal-js and just give a refresh on the page without trouble to check the HTTP_REFERER, since HTTP_REFERER is not 100% guaranteed.

2 answers

4

You can use Session to control whether the user is logged in or not, here is an example of how you could do this control.

PHP

class auth
{
    public static function logged($url)
    {
        if(!$_SESSION['logged'])
            header("location :".$url);          
    }

    public static function login($username, $password)
    {
        if($username == "usuario" && $senha == "senha")
            $_SESSION['logged'] = true;
        else
            return false;

        return true;
    }

    public static function logout()
    {
        if($_SESSION['logged'])
            unset($_SESSION['logged']);
    }   
}

And to make the control on your page do this.

PHP

auth::logged("/login");

You may be using this authentication class to mount the process and adapt to your system.

1

I have tested no further I suggest doing something along those lines:

page that requires login.php:

if (!$_SESSION["logado"]) redirecionar_para_login();

login.php

if (loginSucesso()){
    $pattern = "pt.stackoverflow.com";
    //verifica se foi direcionado de alguma outra página sua
    if(preg_match("/$pattern/i", $_SERVER['HTTP_REFERER']){
        redirecionar_paginaAnterior();
    }
    else{
        redirecionar_paginaPrincipal();
    }
}
redirecionar_paginaAnterior(){
    header("Location: " + $_SERVER['HTTP_REFERER']);
    die();
}

Browser other questions tagged

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