How can session variables be used to control access to specific pages for logged-in users in PHP?
Session variables can be used to control access to specific pages for logged-in users in PHP by setting a session variable upon successful login and checking for the existence of that variable on restricted pages. If the session variable is not set, the user can be redirected to a login page or denied access to the restricted page.
// Start the session
session_start();
// Check if the user is logged in by verifying the session variable
if(!isset($_SESSION['logged_in'])) {
// Redirect the user to the login page
header("Location: login.php");
exit;
}
// Restricted page content here
Related Questions
- How can developers optimize their code to minimize the impact of floating point precision errors in PHP?
- What are the implications of incorrectly labeling form elements in PHP for file uploads?
- How can PHP developers troubleshoot and fix errors related to missing backticks in SQL queries while using CodeIgniter?