0
votes

I have made a login and register system, which works flawlessly, and I am very proud of, but I cannot seem to get a logout function working.

My login system basically takes the database and scans it for rows that have both the username and password specified, and if it does, then it makes $_SESSION['loggedin']=1; and if it fails it makes it equal to 0.

Once the user is done, he/she clicks on a link that redirects to logout.php, and that is where the issues start. I have put session_start(); at the beginning of each page, but session_destroy, session_unset, and combinations of the two cannot seem to kill the session.

So I am wondering, is there a way that upon loading logout.php, it sets the $_SESSION['loggedin] to 0, and then redirects back to index.php(my homepage)? Which means it doesnt kill the session, but it would effectively log the user out. Any help is appreciated.

4
add your code here... - Code Lღver
$_SESSION['loggedin']=0 and then header('Location:'); in your logout.php? - Ignat B.
Why do you set loggedin to 0? Simply dont set it. You can perform checks like if (isset($_SESSION['user']) ){ ... } to check if someone is logged in. I suggest you search arround for some login scripts to see how they work. Proper login is important for security - Martijn

4 Answers

3
votes

// Four steps to closing a session // (i.e. logging out)

    // 1. Find the session
    session_start();

    // 2. Unset all the session variables
    $_SESSION = array();

    // 3. Destroy the session cookie
    if(isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time()-42000, '/');
    }

    // 4. Destroy the session
    session_destroy();
0
votes

if session_destroy doesn't work, use instead:

unset($_SESSION['put your session in here']);

0
votes
// logout.php
session_start();
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 1) {
    $_SESSION['loggedin'] = 0;
    header('Location: index.php');
}

It redirects the user to to index.php, if $_SESSION['loggedin'] equals to 1, and sets $_SESSION['loggedin'] to 0.

0
votes

I suggest you to have 3 files 1) login.php

session_start();
/*if user $_POST username and password is correct then*/
$_SESSION['loggedin'] = 1;

?>

2)logout.php

<?php

session_start();
unset($_SESSION['loggedin']);
$_SESSION['loggedin'] = 0;

?>

3)checkLogin.php

<?php

session_start();
if ( isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == 0 )
{
echo "<script type='text/javascript'>alert('You need to login !')</script>";
echo '<meta http-equiv="Refresh" content="0;URL=index.php" />';
flush();
exit();
}
?>

with 3 files if you want to control some page that require login before access you just include(checkLogin.php);

e.g. index.php is not require login then not include(checkLogin.php);
but memberProfile.php is require login before then include(checkLogin.php);