How can one ensure that PHP code is secure and follows best practices when handling user authentication, such as in a login and register script for a browser game?

To ensure that PHP code for user authentication is secure and follows best practices, it is important to use prepared statements to prevent SQL injection attacks, hash passwords using a strong algorithm like bcrypt, and validate user input to prevent XSS attacks.

// Example of secure user authentication code using prepared statements and password hashing

// Database connection
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Login script
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $_POST['username']]);
$user = $stmt->fetch();

if ($user && password_verify($_POST['password'], $user['password'])) {
    // Successful login
    $_SESSION['user_id'] = $user['id'];
    echo "Login successful!";
} else {
    // Invalid credentials
    echo "Invalid username or password";
}