How can user input for determining the number of images to display be securely handled in PHP to prevent potential security vulnerabilities?

User input for determining the number of images to display should be validated and sanitized to prevent potential security vulnerabilities such as SQL injection or cross-site scripting attacks. This can be achieved by using PHP functions like filter_var() to ensure the input is an integer and within a desired range before using it in any database queries or outputting it to the user.

// Validate and sanitize user input for the number of images to display
$num_images = filter_input(INPUT_GET, 'num_images', FILTER_VALIDATE_INT);

if ($num_images !== false && $num_images > 0 && $num_images <= 10) {
    // Use the sanitized input to determine the number of images to display
    // Your code to display the images here
} else {
    // Handle invalid input, possibly display an error message
    echo "Invalid input for the number of images.";
}