mannia mannia - 1 month ago 6
PHP Question

How to set a cookie to log user out

I'm trying to learn the cookie chapter and need some help understanding when to use them. In this example I want to let user enter his info and then click submit. Then, his info will be displayed. But then I have a logout button and when he presses this, I want the display message to go back to default.

(This is incomplete) but so far I have only written the following in my test.php file:

<?php
session_start();
if(isset($_GET['submit'])) {
$fn = $_GET['fname'];
$ln = $_GET['lname'];
$stunum = $_GET['stunum'];

$_SESSION['firstname'] = $fn;
$_SESSION['lastname'] = $ln;
$_SESSION['studentNumber'] = $stunum;
}

setcookie ('logout', "Logout", time()-3600);
session_destroy();

?>

<html>
<body>
<form action ="message.php" method="get">
Firstname:<br><input type="text" name="fname"><br>
Lastname:<br><input type="text" name="lname"><br>
Student ID:<br><input type="number" name="stunum"><br>
<input type="submit" name="submit">
</form>
</body>
</html>


And in message.php:

<?php
include('test.php');

$firstname = $_SESSION['firstname'];
$lastname = $_SESSION['lastname'];
$studentNumber = $_SESSION['studentNumber'];
echo "Hi " . $firstname . " " . $lastname . "." . "Your student number is " . $studentNumber;

setcookie('logout', "Logout", time() + 3600);
if (isset($_COOKIE['logout'])) {
setcookie('logout', "Logout", time() - 3600);
session_destroy();
}
?>

<html>
<body>
<button name="logout">Logout</button>
</body>
</html>

Answer

You don't need this "logout" cookie at all. Your user is logged in via session so session_destroy(); is more then enough. Good practice is to "destroy" (unset) only that session variables that you have defined ('firstname', 'lastname', 'studentNumber') but not destroy the whole session that can contain data from other scripts.

So if you want to logout user make a form around your "Logout" button and send some variable via POST:

<form action="" method="post">
<button name="logout">Logout</button>
<input type="hidden" name="logout" value="true" />
</form>

And then unset session variables if user submits that form:

if(isset($_POST['logout'])) {
   unset($_SESSION['firstname']);
   unset($_SESSION['lastname']);
   unset($_SESSION['studentNumber']);
}

That's not a good code example but I hope that will help you with your education.