What are the best practices for handling form data in PHP to ensure proper variable passing?

When handling form data in PHP, it is important to properly sanitize and validate user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to ensure proper variable passing is to use PHP's filter_input() function to retrieve form data and apply filters to sanitize and validate the input.

// Retrieve form data using filter_input()
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Check if variables are set and not empty
if(isset($username) && isset($email)){
    // Process the form data
    // ...
} else {
    // Handle form submission errors
    // ...
}