What are best practices for handling user authentication and session management in PHP?
User authentication and session management are crucial aspects of web application security. It is important to securely store user credentials, hash passwords, and validate user input to prevent SQL injection and other attacks. Additionally, using secure session management techniques such as using HTTPS, setting secure flags on cookies, and regularly rotating session IDs can help protect user data.
// Start session
session_start();
// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
// Redirect user to login page
header("Location: login.php");
exit();
}
// Validate user input
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
// Hash password before storing
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Verify password
if(password_verify($password, $hashed_password)) {
// User is authenticated
$_SESSION['user_id'] = $user_id;
// Redirect user to dashboard
header("Location: dashboard.php");
} else {
// Invalid credentials, show error message
echo "Invalid username or password";
}
Keywords
Related Questions
- What are the best practices for sending form data via email in PHP to avoid unexpected errors such as "unexpected T_STRING"?
- In what situations should session variables be passed as parameters to PHP functions for better code structure?
- How can the issue of register_globals affecting the functionality of PHP scripts be addressed in the context of session management?