What are common pitfalls when using session cookies in PHP, and how can they be avoided?

Common pitfalls when using session cookies in PHP include not setting secure and httpOnly flags, not regenerating session IDs, and not properly validating session data. These can be avoided by setting the secure and httpOnly flags on session cookies, regenerating session IDs after successful login, and validating session data before using it.

// Set secure and httpOnly flags on session cookies
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);

// Regenerate session ID after successful login
session_regenerate_id(true);

// Validate session data before using it
if(isset($_SESSION['user_id'])) {
    // Proceed with using the session data
} else {
    // Redirect to login page
    header("Location: login.php");
    exit();
}