How can a PHP session be used to keep a user logged in while performing multiple actions on a website?
To keep a user logged in while performing multiple actions on a website, you can use PHP sessions to store the user's login credentials and check for their validity on each page load. By starting a session when the user logs in and storing their information in session variables, you can maintain their logged-in status across multiple pages until they log out.
// Start the session
session_start();
// Check if the user is logged in
if(isset($_SESSION['user_id'])) {
// User is logged in, perform actions here
} else {
// Redirect to login page if user is not logged in
header("Location: login.php");
exit();
}
Related Questions
- How can PHP developers ensure that no HTML code or echo statements interfere with the header modification for file downloads?
- What are the common pitfalls when exporting a database using phpMyAdmin and how can they be avoided?
- How can .htaccess be used to restrict access to specific files like config.php in a PHP forum?