How can PHP code be optimized to handle user authentication efficiently and securely?

To optimize user authentication in PHP, it is essential to use secure password hashing techniques, such as bcrypt, to store user passwords securely. Additionally, implementing measures like salting passwords and using prepared statements to prevent SQL injection attacks can enhance security. Using session tokens and HTTPS can help ensure secure communication between the user and the server.

// Example PHP code snippet for secure user authentication

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

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

// Prepare SQL statement to retrieve user information
$stmt = $pdo->prepare("SELECT id, username, password FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
$user = $stmt->fetch();

// Verify user password
if ($user && password_verify($password, $user['password'])) {
    // Authentication successful
    session_start();
    $_SESSION['user_id'] = $user['id'];
    echo "Login successful!";
} else {
    // Authentication failed
    echo "Invalid username or password.";
}