How can PHP developers ensure the reliability and efficiency of their code when managing user sessions and authentication?
To ensure the reliability and efficiency of user sessions and authentication in PHP, developers should use secure session handling techniques, validate user input thoroughly, and implement proper password hashing and encryption methods.
// Start a secure session
session_start([
'use_strict_mode' => 1,
'use_cookies' => 1,
'use_only_cookies' => 1,
'cookie_secure' => 1,
'cookie_httponly' => 1
]);
// Validate user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
// Implement password hashing
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Verify user credentials
if ($username === 'admin' && password_verify($password, $hashed_password)) {
$_SESSION['authenticated'] = true;
// Redirect to a secure page
header('Location: secure_page.php');
exit;
} else {
// Display an error message
echo 'Invalid username or password';
}