What are the best practices for handling user authentication and password encryption in PHP scripts?

When handling user authentication and password encryption in PHP scripts, it is crucial to securely store user passwords by hashing them using strong algorithms like bcrypt. Additionally, always use prepared statements or parameterized queries to prevent SQL injection attacks when querying the database for user credentials.

// Hashing user password using bcrypt
$password = 'user_password';
$hashed_password = password_hash($password, PASSWORD_BCRYPT);

// Verifying user password
if (password_verify($password, $hashed_password)) {
    // Password is correct
} else {
    // Password is incorrect
}

// Using prepared statements for querying user credentials
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetch();