What are the best practices for implementing a secure login system in PHP to prevent unauthorized access and account lockouts?

To implement a secure login system in PHP to prevent unauthorized access and account lockouts, it is important to use secure password hashing techniques, implement account lockout mechanisms after multiple failed login attempts, and utilize CSRF tokens to prevent cross-site request forgery attacks.

// Secure password hashing using password_hash() function
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Implement account lockout mechanism after 3 failed login attempts
$login_attempts = 0;
$max_attempts = 3;

if($login_attempts >= $max_attempts){
    // Lock the account and display a message
    echo "Your account has been locked due to multiple failed login attempts.";
} else {
    // Validate login credentials
    if(password_verify($_POST['password'], $hashed_password)){
        // Successful login
    } else {
        // Increment login attempts
        $login_attempts++;
        echo "Invalid login credentials. Attempts left: " . ($max_attempts - $login_attempts);
    }
}

// Generate and validate CSRF tokens
session_start();

if(empty($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']){
    // Invalid CSRF token
    die("CSRF token validation failed.");
} else {
    // Valid CSRF token
}