What best practices should be followed when handling user authentication in PHP?

When handling user authentication in PHP, it is important to follow best practices to ensure the security of user data. This includes using secure password hashing algorithms like bcrypt, storing passwords securely in the database, and implementing measures to prevent common security vulnerabilities like SQL injection and cross-site scripting attacks.

// Example code snippet for user authentication in PHP using bcrypt password hashing

// Retrieve user input from form
$username = $_POST['username'];
$password = $_POST['password'];

// Retrieve hashed password from database based on username
$hashedPassword = ''; // Retrieve hashed password from database query

// Verify password using password_verify function
if (password_verify($password, $hashedPassword)) {
    // Password is correct, authenticate user
    echo 'User authenticated successfully';
} else {
    // Password is incorrect, show error message
    echo 'Invalid username or password';
}