What are best practices for handling user authentication in PHP to prevent security vulnerabilities?

To prevent security vulnerabilities in user authentication in PHP, it is important to use secure password hashing techniques such as bcrypt, implement measures to prevent SQL injection attacks, and use prepared statements for database queries.

// Example of secure user authentication in PHP using bcrypt hashing and prepared statements

// Verify user credentials
$username = $_POST['username'];
$password = $_POST['password'];

// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

// Verify password using password_verify function
if ($user && password_verify($password, $user['password'])) {
    // Authentication successful
    echo "Login successful";
} else {
    // Authentication failed
    echo "Login failed";
}