简体   繁体   中英

How to destroy session and log out

I have a login page and a main page. On the login page I am asking for Username and Password and on the main page I m displaying some values from the database. Problem is with the logout function. I am doing it like this:

login.php Page

<?php
session_start();

if (isset($_POST['submit'])) {
    //log in code and to go to main.php
}

if (isset($_REQUEST['logstate'])) {
    session_destroy();
}

?>

main.php Page

<a href="login.php?logstate=logout"><img src="logout.png" id="Logout"></a>

Now when I click on the log out image, it ends the session, but returns me with the URL: xxxxx.com/login.php?logstate=logout

I want it to return me the url: xxxxx.com/login.php

You can try to redirect

<?php
session_start();

if (isset($_POST['submit'])) {
    //log in code and to go to main.php
}

if (isset($_REQUEST['logstate'])) {
    session_destroy();
    header("Location: xxxxx.com/login.php");
}

?>

you can try this on logout

you can call the file logout.php on logout image and code is :

<?php 
session_start();
session_destroy();
header("Location:home.php");//change the filename where you want to redirect it after logout
?>

OR in your way :

if(isset($_REQUEST['logstate']))
{
  session_destroy();
  header("Location:home.php");//change the filename where you want to redirect it after logout
}

See the Session_destroy() Doc , Initialize the session is necessary while destroying the session.

You need to do a redirect

if(isset($_REQUEST['logstate']))
{
  session_destroy();
  header( 'Location: /login.php' ) ;
}

Just redirect the user after destroying the session.

<?php
header('Location: http://www.example.com/login.php');
exit;
?>

Try it It will solve your problem:

 <?php
    session_start();

    if(isset($_POST['submit']))
    {
      //log in code and to go to main.php
    }

    if(isset($_REQUEST['logstate']))
    {
      session_destroy();
    header("location: xxxxx.com/login.php"); 
    exit();
    }

?>

make this your logout.php file and use it as a link to logout button

    <?php 
    session_start();
    session_destroy();
    header("Location:yourlocation.php");
    exit;
    ?>

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