What are best practices for handling user-selected values in PHP forms?

When handling user-selected values in PHP forms, it is important to validate and sanitize the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One best practice is to use PHP's filter_input function to retrieve and sanitize user input from form fields.

// Retrieve and sanitize user-selected value from a form field
$userInput = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

// Validate the user-selected value
if ($userInput) {
    // Process the user-selected value
    // (e.g. store in a database, display on a webpage, etc.)
} else {
    // Handle invalid input (e.g. display an error message)
}