What are some best practices for implementing user authentication in PHP and MySQL projects?
Issue: Implementing user authentication in PHP and MySQL projects requires securely storing user passwords, validating user credentials, and protecting against SQL injection attacks.
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Securely store user password using password_hash()
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
// Validate user credentials
$query = "SELECT * FROM users WHERE username = ? AND password = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $_POST['username'], $password);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1) {
// User authentication successful
echo "Welcome, ".$_POST['username']."!";
} else {
// User authentication failed
echo "Invalid username or password.";
}
// Protect against SQL injection attacks
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
$stmt->bind_param("ss", $username, $password);