What best practices should be followed when implementing login functionality in PHP using sessions?
When implementing login functionality in PHP using sessions, it is important to follow best practices to ensure security and reliability. This includes properly sanitizing user input, using password hashing for storing passwords, and validating user credentials before creating a session.
<?php
session_start();
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize user input
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$password = filter_var($_POST["password"], FILTER_SANITIZE_STRING);
// Validate user credentials (example only, implement your own validation logic)
if ($username === "admin" && password_verify($password, '$2y$10$9mXrBk7NwF2ZrD6qHk9mOuV3IY2X7kQ2tni6qGzA3mHn2o3gXJ3A2')) {
// Set session variables
$_SESSION["username"] = $username;
// Redirect to dashboard or home page
header("Location: dashboard.php");
exit();
} else {
echo "Invalid username or password";
}
}
?>
Keywords
Related Questions
- What are the potential pitfalls when using session variables in PHP scripts for sequential calls?
- What are some best practices for debugging issues with sending attachments via PHPMailer?
- What are the advantages of using mysql_num_rows() over a while loop when checking for existing data in a database query result?