Are there best practices for handling user authentication and session management in PHP scripts to prevent unauthorized access?
To prevent unauthorized access in PHP scripts, it is essential to implement secure user authentication and session management practices. This includes using strong password hashing algorithms, validating user input, implementing CSRF protection, and ensuring session data is securely stored and managed.
// Start the session
session_start();
// Check if the user is authenticated
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
// Redirect to the login page
header('Location: login.php');
exit();
}
// Validate user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
// Verify user credentials
if ($username === 'admin' && password_verify($password, '$2y$10$S3UuNw2dW8J6j4wJfKqoP.F5W5M8WY2fJH1gDjJ6t8l5Vz.4oqN3a')) {
$_SESSION['authenticated'] = true;
} else {
// Redirect to the login page
header('Location: login.php');
exit();
}