What are best practices for handling user authentication and login systems in PHP using MySQL databases?
Issue: When handling user authentication and login systems in PHP using MySQL databases, it is important to securely store user passwords, validate user credentials, and protect against SQL injection attacks.
// Example of handling user authentication and login in PHP using MySQL
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
// Securely hash the password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Validate user credentials
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $mysqli->query($query);
if ($result->num_rows == 1) {
$user = $result->fetch_assoc();
if (password_verify($password, $user["password"])) {
// User authenticated, redirect to dashboard
header("Location: dashboard.php");
exit();
} else {
// Invalid password
echo "Invalid password";
}
} else {
// User not found
echo "User not found";
}
}