What are the best practices for handling user authentication and session management in PHP login scripts?

User authentication and session management are crucial components of PHP login scripts to ensure secure access to user accounts. Best practices include using secure hashing algorithms for storing passwords, implementing CSRF protection, using prepared statements to prevent SQL injection attacks, and setting secure session cookies.

// User authentication
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Session management
session_start();
$_SESSION['user_id'] = $user_id;

// Setting secure session cookies
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);