What best practices should be followed when working with form data and session variables in PHP to avoid issues like only partial data being stored or accessed?

When working with form data and session variables in PHP, it is important to ensure that all necessary data is properly stored and accessed. One common issue is only partial data being stored or accessed due to improper handling of form submissions or session variables. To avoid this, always validate and sanitize form data before storing it in session variables, and make sure to properly retrieve and handle session variables when accessing them.

// Validate and sanitize form data before storing in session
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    
    // Store validated data in session variables
    $_SESSION["username"] = $username;
    $_SESSION["email"] = $email;
}

// Retrieve and handle session variables properly
if (isset($_SESSION["username"]) && isset($_SESSION["email"])) {
    $username = $_SESSION["username"];
    $email = $_SESSION["email"];
    
    // Use the retrieved data as needed
    echo "Username: " . $username . "<br>";
    echo "Email: " . $email;
}