What are the best practices for handling variables passed through URLs in PHP to prevent security vulnerabilities?

When handling variables passed through URLs in PHP, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. One way to do this is by using PHP's filter_input function with the FILTER_SANITIZE_STRING or FILTER_SANITIZE_NUMBER_INT filter flags to clean the input before using it in your application.

// Sanitize and validate input from URL
$user_id = filter_input(INPUT_GET, 'user_id', FILTER_SANITIZE_NUMBER_INT);

if ($user_id === false) {
    // Invalid input, handle error
} else {
    // Use the sanitized user_id in your application
}