如何在PHP中单击“注销”按钮后禁用浏览器后退按钮功能

时间:2022-11-15 01:18:05

I am having trouble with the browser back button. When the User press Log out it have to destroy the session and cookies. I wrote the following code:

我在使用浏览器后退按钮时遇到问题。当用户按下注销时,它必须销毁会话和cookie。我写了以下代码:

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript">
        function disablebackbutton(){
            window.history.forward();
        }
        disablebackbutton();
    </script>
</head>
<body>
<form name="loginform" method="post" action="<?php echo __PROJECT_LINK__; ?>/php/login_exec.php">
                <div class="modal-body">
                    <div class="form-horizontal">
                        <div class="form-group">
                            <label class="control-label">
                                <?php
                                if( isset($_SESSION['ERRMsg_ARR']) && is_array($_SESSION['ERRMsg_ARR']) && count($_SESSION['ERRMsg_ARR']) >0 ) {
                                    echo '<ul class="err">';
                                    foreach($_SESSION['ERRMsg_ARR'] as $msg) {
                                        echo '<span class="label label-warning" style="margin-left: 5px;">',$msg,'</span>';
                                    }
                                    echo '</ul>';
                                    unset($_SESSION['ERRMsg_ARR']);
                                }
                                ?>
                            </label>
                        </div>
                        <div class="subnav subnav-fixed nav navbar" style="margin-top: 10px; margin-right: 10px; margin-left: 10px;">
                            <ul class="nav nav-pills">
                                <li style="margin-top: 10px;">
                                    <span class="label label-default" style="margin-left: 22px;">Username</span>
                                    <input type="text" id="inputUserName" name="username" placeholder="Username" style="margin-left: 5px;">
                                </li>
                                <li style="margin-top: 10px;">
                                    <span class="label label-default" style="margin-left: 22px;">Password</span>
                                    <input type="password" id="inputPassword" name="password" placeholder="Password" style="margin-left: 5px;">
                                </li>
                                <li style="margin-top: 10px; margin-bottom: 10px;">
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <!--?php $this->btnLogLogin->Render();?-->
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Sign In</button>
                </div>
            </form>
</body>
</html>

login_exec.php

<?php
    //Start session
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    //Include database connection details
    require_once('connection.php');

    //Array to store validation errors
    $errmsg_arr = array();

    //Validation error flag
    $errflag = false;

    //Function to sanitize values received from the form. Prevents SQL injection
    function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
    $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
    }
     if(isset($_POST['username']))
     {
    //Sanitize the POST values
    $username = ($_POST['username']);
    $password = ($_POST['password']);

    //Input Validations
    if($username == '') {
    $errmsg_arr[] = 'Username missing';
    $errflag = true;
    }
    if($password == '') {
    $errmsg_arr[] = 'Password missing';
    $errflag = true;
    }

    //If there are input validations, redirect back to the login form
    if($errflag==true) {
    $_SESSION['ERRMsg_ARR'] = $errmsg_arr;
    session_write_close();
    header("location:../index.php");
    exit();
    }

    //Create query
    $qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
    $result=mysql_query($qry);

    //Check whether the query was successful or not
    if($result) {
    if(mysql_num_rows($result)) {
        while($row = mysql_fetch_array($result))
        {
            if($row['User_Status']=="Active"){
                $expire=time()+60*60*24*30; //1month
                setcookie("User_id", $row['User_id'], $expire);
                $name = $row['full_name'];
                $parts = explode(" ", $name);
                $lastname = array_pop($parts);
                $firstname = implode(" ", $parts);
                $_SESSION['USER']  = $firstname;
                $_SESSION['UID']  = $row['User_id'];
                $_SESSION['URights'] = $row['Rights'];
                header("location:../welcome.php");
            }
            else{
                $errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
                $errflag = true;
                if($errflag) {
                    $_SESSION['ERRMsg_ARR'] = $errmsg_arr;
                    session_write_close();
                    header("location: ../index.php");
                    exit();
                }
            }
        }
    }
    else {
    //Login failed
    $errmsg_arr[] = 'Username and Password not found';
    $errflag = true;
    if($errflag) {
    $_SESSION['ERRMsg_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: ../index.php");
    exit();
    }
    }
    }else {
    die("Query failed");
    }
    }
    ?>

welcome.php

<?php include 'qcubed.inc.php'; ?>
<?php
    $User_Name = $_SESSION['USER'];
    ?>
<html>

   <head>
      <title>Welcome</title>
   </head>
   <body>
      <h1>Welcome <?php echo $User_Name; ?></h1>
      <h2><a href = "<?php echo __PROJECT_LINK__; ?>/Info.php">Info</a></h2> 
      <h2><a href = "<?php echo __PROJECT_LINK__; ?>/php/logout.php">Sign Out</a></h2>
   </body>
 </html>

Info.php

    <?php include '../../qcubed.inc.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?php echo __PROJECT_TITLE__; ?> - Full Info</title>
    <script type="text/javascript">
            function disablebackbutton(){
                window.history.forward();
            }
            disablebackbutton();
        </script>
</head>
<?php
if(isset($_SESSION['UID']) && $_SESSION['UID'] != "")
{
//Task to do
        $User_Name = $_SESSION['USER'];
?>
<body>
         <h1>Info about <?php echo $User_Name; ?></h1> 
          <h2><a href = "<?php echo __PROJECT_LINK__; ?>/php/logout.php">Sign Out</a></h2>
       </body>
<?php
}
else{
    //redirect URL
    ?>
       <script>
            alert('You must Login first.');
            window.location.href='../../index.php';
        </script>";
   <?php

    exit();
}
?>

     </html>

logout.php

<?php
//session_write_close();
    session_start(); # NOTE THE SESSION START
    $expire=time()-60*60*24*30; //1month
    if(isset($_COOKIE['User_id'])):
        setcookie('User_id', '', $expire, '/');
    endif;
    unset($_SESSION['UID']);
    unset($_SESSION['USER']);
    unset($_SESSION['URights']);
    unset($_SESSION['UReg']);
    $_SESSION = array();
    foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
    session_unset();
    session_destroy();
    header("location: ../index.php");
    exit(); # NOTE THE EXIT
?>

After pressing log out from Info.php , when I press the browser back button it is showing my previous Logined user page and session username in Info.php page, but if I use the following javascript in head section of every page it disable all the browser back button at the time of login also.

按下从Info.php注销后,当我按下浏览器后退按钮时,它在Info.php页面中显示我之前登录的用户页面和会话用户名,但是如果我在每个页面的head部分使用以下javascript则禁用所有登录时的浏览器后退按钮也是。

<script type="text/javascript">
        function disablebackbutton(){
            window.history.forward();
        }
        disablebackbutton();
    </script>

I want to disable the browser back button only after the the time of logout. Please help me.

我想在注销时才禁用浏览器后退按钮。请帮我。

5 个解决方案

#1


0  

That became my problem before. On my case i did not disable the back button. what i did is to check the session when the user is logged out. if there has no detected session, redirect the user to log in page or to what page you like the to redirect.. if there is a detected session redirect it to the homepage

这成了我以前的问题。在我的情况下,我没有禁用后退按钮。我所做的是在用户注销时检查会话。如果没有检测到会话,请将用户重定向到登录页面或重定向到您要重定向的页面..如果检测到的会话将其重定向到主页

#2


0  

rather than disabling the back button, you can add code to every page to see if the user is logged. If they are NOT logged in, redirect to the login page.

您可以向每个页面添加代码,以查看用户是否已记录,而不是禁用后退按钮。如果他们未登录,请重定向到登录页面。

You could create a basic class to handle this for you and just create one on every page.

您可以创建一个基本类来为您处理此问题,并在每个页面上创建一个。

class sessionHandler
{

    function __construct($special = NULL)
    {

        session_set_cookie_params(60 * 60 * 24 * 365); // 1 year
        session_start();

        // if no user num (empty session) AND this isn't the login page
        if (!isset($_SESSION['userID']) && $special != 'LOGIN') {
            //send to login page
            header("location: login.php");
        }

        if ($special == 'LOGOUT') {
            // This is the logout page, clear the session and
            // send the user to the afterLogout page

            session_destroy();   // clear session files on server
            $_SESSION = Array(); // clear session variable for this session
            unset($_SESSION);

            // send to login page
            header("location: login.php");
        }

        if ($special == 'LOGIN') {
            // This is the login page, see if user is already logged in
            // if so, just send them to the afterLogin page
            // if not, validate their credentials, and store the USERID
            // in the $_SESSION var

            if ($this->getUserPermissions($_SESSION['userID'])) {
                 // send to any page you want
                 header("location: dashboard.php");
            }

        }

    }
}

Now, on all your pages, put $session = new sessionHandler(); at the top (before anything else is written.

现在,在你的所有页面上,放入$ session = new sessionHandler();在顶部(在编写任何其他内容之前)。

For login and logout pages you'd put: $session = new sessionHandler('LOGIN'); $session = new sessionHandler('LOGOUT');

对于登录和注销页面,您需要:$ session = new sessionHandler('LOGIN'); $ session = new sessionHandler('LOGOUT');

Not copy and paste ready, but hopefully that points you in the right direction. :-)

不要复制和粘贴准备好,但希望能指出正确的方向。 :-)

#3


0  

USE THIS CODE in login_exec.php

在login_exec.php中使用此代码

 if($errflag==true) {
        $_SESSION['ERRMsg_ARR'] = $errmsg_arr;
        session_write_close();
        header("location:../index.php");
        exit();
        }

        //Create query
        $qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
        $result=mysql_query($qry);

        //Check whether the query was successful or not
        if($result) {
        if(mysql_num_rows($result)) {
            while($row = mysql_fetch_array($result))
            {
                if($row['User_Status']=="Active"){
                    $expire=time()+60*60*24*30; //1month
                    setcookie("User_id", $row['User_id'], $expire);
                    $name = $row['full_name'];
                    $parts = explode(" ", $name);
                    $lastname = array_pop($parts);
                    $firstname = implode(" ", $parts);
                    $_SESSION['USER']  = $firstname;
                    $_SESSION['UID']  = $row['User_id'];
                    $_SESSION['login']=true; //ADD THIS CODE IN login_exec.php
                    $_SESSION['URights'] = $row['Rights'];
                    header("location:../welcome.php");
                }
                else{
                    $errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
                    $errflag = true;
                    if($errflag) {
                        $_SESSION['ERRMsg_ARR'] = $errmsg_arr;
                        session_write_close();
                        header("location: ../index.php");
                        exit();
                    }
                }
            }
        }

now add the code top of the info.php

现在添加info.php的代码顶部

    session_start();
    $user=$_SESSION['USER'];
    if($_session['login']=true && $_session['user']= $user)
    {

    code of info.php 
    }
else
{

header(location:index.php);
}

logout.php

<?php
    session_start();
    unset($_SESSION['USER']);
    session_destroy();
    header("Location:index.php");
?>

#4


0  

Just add a condition at all the pages which user can access only if he is login:

只需在用户可以访问的所有页面上添加条件:

if(!isset($_SESSION['UID']) || $_SESSION['UID'] == ''){
    // redirect to index or login page
}

#5


0  

At last I solved my problem ..... :-) I use this following code in

最后我解决了我的问题..... :-)我使用下面的代码

logout.php

<html>
<head>
    <script type = "text/javascript" >
    window.history.forward();
    function preventBack() { window.history.forward(1); }
    setTimeout("preventBack()", 0);
    window.onunload = function () { null };
</script>

</head>
<body onload="preventBack();" onpageshow="if (event.persisted) preventBack();" onunload="">
Please Wait..
<?php

session_start(); # NOTE THE SESSION START
$expire=time()-60*60*24*30; //1month
if(isset($_COOKIE['User_id'])){
    setcookie('User_id', '', $expire);
}
unset($_SESSION['UID']);
unset($_SESSION['USER']);
unset($_SESSION['URights']);
unset($_SESSION['UReg']);
$_SESSION = array();
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
session_unset();
session_destroy();

header("Refresh: 2;url=../index.php");
?>
</body>
</html>

Now it's avoid me to use browser back button after logout and destroy the session. Thank you all for yours valuable support...

现在它可以避免我在注销后使用浏览器后退按钮并销毁会话。谢谢大家的宝贵支持......

#1


0  

That became my problem before. On my case i did not disable the back button. what i did is to check the session when the user is logged out. if there has no detected session, redirect the user to log in page or to what page you like the to redirect.. if there is a detected session redirect it to the homepage

这成了我以前的问题。在我的情况下,我没有禁用后退按钮。我所做的是在用户注销时检查会话。如果没有检测到会话,请将用户重定向到登录页面或重定向到您要重定向的页面..如果检测到的会话将其重定向到主页

#2


0  

rather than disabling the back button, you can add code to every page to see if the user is logged. If they are NOT logged in, redirect to the login page.

您可以向每个页面添加代码,以查看用户是否已记录,而不是禁用后退按钮。如果他们未登录,请重定向到登录页面。

You could create a basic class to handle this for you and just create one on every page.

您可以创建一个基本类来为您处理此问题,并在每个页面上创建一个。

class sessionHandler
{

    function __construct($special = NULL)
    {

        session_set_cookie_params(60 * 60 * 24 * 365); // 1 year
        session_start();

        // if no user num (empty session) AND this isn't the login page
        if (!isset($_SESSION['userID']) && $special != 'LOGIN') {
            //send to login page
            header("location: login.php");
        }

        if ($special == 'LOGOUT') {
            // This is the logout page, clear the session and
            // send the user to the afterLogout page

            session_destroy();   // clear session files on server
            $_SESSION = Array(); // clear session variable for this session
            unset($_SESSION);

            // send to login page
            header("location: login.php");
        }

        if ($special == 'LOGIN') {
            // This is the login page, see if user is already logged in
            // if so, just send them to the afterLogin page
            // if not, validate their credentials, and store the USERID
            // in the $_SESSION var

            if ($this->getUserPermissions($_SESSION['userID'])) {
                 // send to any page you want
                 header("location: dashboard.php");
            }

        }

    }
}

Now, on all your pages, put $session = new sessionHandler(); at the top (before anything else is written.

现在,在你的所有页面上,放入$ session = new sessionHandler();在顶部(在编写任何其他内容之前)。

For login and logout pages you'd put: $session = new sessionHandler('LOGIN'); $session = new sessionHandler('LOGOUT');

对于登录和注销页面,您需要:$ session = new sessionHandler('LOGIN'); $ session = new sessionHandler('LOGOUT');

Not copy and paste ready, but hopefully that points you in the right direction. :-)

不要复制和粘贴准备好,但希望能指出正确的方向。 :-)

#3


0  

USE THIS CODE in login_exec.php

在login_exec.php中使用此代码

 if($errflag==true) {
        $_SESSION['ERRMsg_ARR'] = $errmsg_arr;
        session_write_close();
        header("location:../index.php");
        exit();
        }

        //Create query
        $qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
        $result=mysql_query($qry);

        //Check whether the query was successful or not
        if($result) {
        if(mysql_num_rows($result)) {
            while($row = mysql_fetch_array($result))
            {
                if($row['User_Status']=="Active"){
                    $expire=time()+60*60*24*30; //1month
                    setcookie("User_id", $row['User_id'], $expire);
                    $name = $row['full_name'];
                    $parts = explode(" ", $name);
                    $lastname = array_pop($parts);
                    $firstname = implode(" ", $parts);
                    $_SESSION['USER']  = $firstname;
                    $_SESSION['UID']  = $row['User_id'];
                    $_SESSION['login']=true; //ADD THIS CODE IN login_exec.php
                    $_SESSION['URights'] = $row['Rights'];
                    header("location:../welcome.php");
                }
                else{
                    $errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
                    $errflag = true;
                    if($errflag) {
                        $_SESSION['ERRMsg_ARR'] = $errmsg_arr;
                        session_write_close();
                        header("location: ../index.php");
                        exit();
                    }
                }
            }
        }

now add the code top of the info.php

现在添加info.php的代码顶部

    session_start();
    $user=$_SESSION['USER'];
    if($_session['login']=true && $_session['user']= $user)
    {

    code of info.php 
    }
else
{

header(location:index.php);
}

logout.php

<?php
    session_start();
    unset($_SESSION['USER']);
    session_destroy();
    header("Location:index.php");
?>

#4


0  

Just add a condition at all the pages which user can access only if he is login:

只需在用户可以访问的所有页面上添加条件:

if(!isset($_SESSION['UID']) || $_SESSION['UID'] == ''){
    // redirect to index or login page
}

#5


0  

At last I solved my problem ..... :-) I use this following code in

最后我解决了我的问题..... :-)我使用下面的代码

logout.php

<html>
<head>
    <script type = "text/javascript" >
    window.history.forward();
    function preventBack() { window.history.forward(1); }
    setTimeout("preventBack()", 0);
    window.onunload = function () { null };
</script>

</head>
<body onload="preventBack();" onpageshow="if (event.persisted) preventBack();" onunload="">
Please Wait..
<?php

session_start(); # NOTE THE SESSION START
$expire=time()-60*60*24*30; //1month
if(isset($_COOKIE['User_id'])){
    setcookie('User_id', '', $expire);
}
unset($_SESSION['UID']);
unset($_SESSION['USER']);
unset($_SESSION['URights']);
unset($_SESSION['UReg']);
$_SESSION = array();
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
session_unset();
session_destroy();

header("Refresh: 2;url=../index.php");
?>
</body>
</html>

Now it's avoid me to use browser back button after logout and destroy the session. Thank you all for yours valuable support...

现在它可以避免我在注销后使用浏览器后退按钮并销毁会话。谢谢大家的宝贵支持......