0

I have a logout button which doesn't seem to work well. After clicking on it I can still see the "Welcome username" and the logout button is still there as in the picture below. Please let me know what's missing on my logout.php.

May I also ask how I could redirect the user back to the orginal page after clicking logout ? I try to use "header('Location: ' . $_SERVER['HTTP_REFERER']);" but it doesn't work ?

enter image description here
Index.php

<?php
ini_set("session.save_path", "sessionData");
session_start();
?>

 <?php if (!isset($_SESSION['uName'])) { ?>
    <form method="post" action="logonProcess.php">
    <div>Username <input type="text" name="userName" placeholder="Username"></div>
    <div>Password <input type="password" name="pwd" placeholder="Password"></div>
    <div><input type="submit" value="Logon"></div>
    </form>
<?php } else { }?>



<?php if (isset($_SESSION['uName'])) { 
    $username = $_SESSION['uName'];     
    echo "<p>Welcome $username</p>\n";
?>
        <a href="logout.php">Logout</a>

<?php } else { }?>

Logout.php

<?php
unset($_SESSION['user']);
session_destroy(); // Destroying All Sessions
header("Location: index.php"); // Redirecting To Home Page
?> 
Barmar
  • 741,623
  • 53
  • 500
  • 612
Doran L
  • 299
  • 2
  • 5
  • 19
  • Take a look at the manual about the referrer, http://php.net/manual/en/reserved.variables.server.php. It isn't always set. Should check and have a default if not `Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.`. – chris85 Nov 26 '15 at 02:41
  • 1
    Have you tried [This one](http://stackoverflow.com/a/3512570/3583859) Accepted Answer – Vijay Kumbhoje Nov 26 '15 at 02:41
  • Why are you unsetting a different session variable than the one you set? – Barmar Nov 26 '15 at 02:48
  • 1
    @Vijay Thanks that work – Doran L Nov 26 '15 at 03:00
  • @Barmar thanks for pointing that out – Doran L Nov 26 '15 at 03:00

3 Answers3

2

Try starting session first:

Logout.php

<?php
  session_start();
  unset($_SESSION['uName']);
  session_destroy(); // Destroying All Sessions
  header("Location: index.php"); // Redirecting To Home Page
?> 

source from: http://www.hackingwithphp.com/10/3/5/ending-a-session

Ceeee
  • 1,392
  • 2
  • 15
  • 32
1

try adding this to your logout file:

unset($_SESSION['uName']);
Tivie
  • 18,864
  • 5
  • 58
  • 77
1

All your scripts that use sessions need to use the same session.save_path setting. Since you set that in index.php, you also need to set it in logout.php. Otherwise, logout.php won't be able to access the session data.

Barmar
  • 741,623
  • 53
  • 500
  • 612