How can PHP scripts be optimized to handle user logins and sessions more efficiently?
To optimize PHP scripts for handling user logins and sessions more efficiently, you can utilize session variables to store user information securely and use cookies to maintain user sessions across multiple pages. Additionally, you can implement server-side validation for user credentials to ensure secure authentication.
// Start a session
session_start();
// Check if user is already logged in
if(isset($_SESSION['user_id'])) {
// User is already logged in, redirect to dashboard
header('Location: dashboard.php');
exit();
}
// Validate user credentials
if($_POST['username'] == 'admin' && $_POST['password'] == 'password') {
// Set session variables
$_SESSION['user_id'] = 1;
$_SESSION['username'] = 'admin';
// Redirect to dashboard
header('Location: dashboard.php');
exit();
} else {
// Invalid credentials, display error message
echo 'Invalid username or password';
}