How can PHP sessions be used to restrict access to certain pages until a user is logged in?
To restrict access to certain pages until a user is logged in, PHP sessions can be used to track the user's login status. When a user successfully logs in, a session variable can be set to indicate that the user is authenticated. On restricted pages, this session variable can be checked, and if the user is not logged in, they can be redirected to a login page.
<?php
session_start();
// Check if user is not logged in, redirect to login page
if(!isset($_SESSION['loggedin'])) {
header("Location: login.php");
exit();
}
?>
Related Questions
- In PHP, what are some common debugging techniques for resolving syntax errors and ensuring the accuracy of database query results displayed on the frontend?
- What are some common mistakes to avoid when working with data retrieved from a database in PHP?
- What are the potential pitfalls of using quotation marks around variables in PHP arrays?