简体   繁体   中英

Log out user from php session

When a user is logged in, I want them to have a button to log out and be redirected to the page they are on, however, with a few additional features, which are called. Unfortunately, nothing happens when the log out button is pressed.

This is the code for the logout.php file.

<input type="submit" type="submit" name="submit" value="Log out">
<?php
    if (isset($_POST['submit'])){
       session_start();
       $_SESSION = array();
       if (ini_get("session.use_cookies")) {
       $yesterday = time() - (24 * 60 * 60); $params = session_get_cookie_params();            
       setcookie(session_name(), '', $yesterday,
       $params["path"], $params["domain"],
       $params["secure"], $params["httponly"] );
     }
     session_destroy();
     header('Location: '.$_SERVER['PHP_SELF']);
   }
 ?>
  1. Redirect user to a logout php script (logout.php)
  2. Continue the session by calling session_start()
  3. Check if $_SESSION['uname'] is empty or not... if empty then destroy the session by calling session_destroy()
  4. Redirect the user back to the home page header("/")

//HTML

<a href="logout.php">logout</a>

-or-

<input type="button" value="Logout" onclick="window.location.href = 'logout.php';">

-or-

<button onclick="window.location.href = 'logout.php';">Logout</button>

//LOGOUT.PHP

<?php
//continue current session
session_start();
//check to see if session variable (uname) is set
//if set destroy the session
if(!empty($_SESSION['uname'])){
    session_destroy();
}
//redirect the user to the home page
header("Location: /");
?>

Just save it as " login.php " and access from the browser. UserId is " user " and Password is " pass ".

<?php session_start(); ?>
<?php if ( array_key_exists( 'uid', $_SESSION ) ): ?>
    <?php /* if $_SESSION['uid'] is set, user is already logged in */ ?>
    <?php if ( array_key_exists( 'cmd', $_GET ) && $_GET['cmd']==='logout' ): ?>
        <?php
            unset( $_SESSION[ 'uid' ] );
            unset( $_SESSION[ 'error' ] );
            session_destroy();
        ?>
        <h1>See you soon!</h1>
        Click 
        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?r=<?php echo md5(uniqid(rand())); ?>">here</a>
        if you don&#39;t get redirected automatically within 5 seconds.
        <script type="text/javascript">
            setTimeout( function() { 
                location.href = "<?php echo addslashes( $_SERVER['PHP_SELF'] ); ?>?r=<?php echo md5(uniqid(rand())); ?>"; 
              }, 5000 );
        </script>
    <?php else: ?>
        <h1>You are logged in</h1>
        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?cmd=logout&amp;r=<?php echo md5(uniqid(rand())); ?>">Log Out</a> | 
        <a href="<?php echo $_SERVER['PHP_SELF']; ?>?r=<?php echo md5(uniqid(rand())); ?>">Refresh</a>
    <?php endif; ?>
<?php else: ?>
    <?php /* user is not logged in */ ?>
    <?php if ( strtolower($_SERVER['REQUEST_METHOD']) == 'post' ): ?>
        <?php
            // login (POST) request, let's check if credentials 
            // are correct
            unset( $_SESSION['error'] );
            if ( array_key_exists( 'userid', $_POST ) && array_key_exists( 'passwd', $_POST ) )
                {
                    $userid = trim( $_POST['userid'] );
                    $passwd = trim( $_POST['passwd'] );
                    if ( $userid === '' )
                        {
                            $_SESSION['error'] = 'No userid supplied';
                        }
                    elseif ( $passwd === '' )
                        {
                            $_SESSION['error'] = 'No password supplied';
                        }
                    elseif ( $userid !== 'user' || $passwd !== 'pass' )
                        {
                            $_SESSION['error'] = 'Wrong userid or password';
                        }
                    else
                        {
                            $_SESSION['uid'] = $userid;
                            // from now on, the user is logged in
                        }
                }
            else
                {
                    $_SESSION['error'] = 'Missing userid or password';
                }

            // redirect the user anyways
            // this gets rid of posted data if this was a POST,
            // so when user reloads the page it doesn't try to
            // re-authenticate
            // Can be a different URL if user is logged in 
            // successfully
            header( 'Location: ' . $_SERVER['PHP_SELF'] . '?r=' . md5(uniqid(rand())) );
            exit;
        ?>
    <?php else: ?>
        <?php /* user not logged in, let's display login form */ ?>
        <h1>Log In</h1>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
            <label for="user-id">User Id</label>
            <input type="text" name="userid" id="user-id" />
            <label for="user-pwd">Password</label>
            <input type="password" name="passwd" id="user-pwd" />
            <input type="submit" value="Log In" />
        </form>
        <?php /* in case any errors occured, show them */ ?>
        <?php if ( array_key_exists( 'error', $_SESSION ) && $_SESSION['error'] ): ?>
            <div class="error-msg"><?php echo $_SESSION['error']; ?></div>
        <?php endif; ?>
    <?php endif; ?>
<?php endif; ?>

In any other (PHP) page of your site, you can then restrict access to authenticated users by checking:

<?php
    if ( array_key_exists( 'uid', $_SESSION ) )
        {
            /* user is logged in, do whatever */
        }
    else
        {
            /* user is NOT logged in, do whatever else */
        }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM