What are some best practices for handling user input in PHP, especially when elements are unpredictable or need to be uniquely identified?

When handling user input in PHP, especially when elements are unpredictable or need to be uniquely identified, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to handle this is by using PHP's filter_input function along with filters like FILTER_SANITIZE_STRING or FILTER_VALIDATE_INT to ensure that the input is safe and meets the expected format.

// Example of handling user input in PHP using filter_input

// Sanitize and validate input
$userInput = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

if ($userInput) {
    // Process the sanitized input
    echo "User input: " . $userInput;
} else {
    // Handle invalid input
    echo "Invalid input detected";
}