What is the recommended method to handle logout in a session-based login system using PHP?
In a session-based login system using PHP, the recommended method to handle logout is to destroy the session data associated with the user when they choose to logout. This ensures that the user is effectively logged out and their session is terminated.
<?php
session_start();
// Check if user is logged in
if(isset($_SESSION['user_id'])) {
// Unset all session variables
$_SESSION = array();
// Destroy the session
session_destroy();
// Redirect to login page or any other desired page
header("Location: login.php");
exit;
} else {
// Redirect to login page if user is not logged in
header("Location: login.php");
exit;
}
?>
Keywords
Related Questions
- What potential pitfalls should be considered when using timestamps in file names with PHP?
- What steps can be taken to troubleshoot when a PHP script, like the thermometer generator, does not display the expected output?
- Are there specific PHP scripts or plugins that can cause caching issues for PHP pages?