What best practices should be followed when dynamically loading images based on URL parameters in PHP?
When dynamically loading images based on URL parameters in PHP, it is important to sanitize and validate the input to prevent security risks such as injection attacks. One way to achieve this is by using PHP's filter_input() function to retrieve and validate the URL parameters before using them to load the images.
<?php
// Sanitize and validate the URL parameter
$imageId = filter_input(INPUT_GET, 'image_id', FILTER_SANITIZE_NUMBER_INT);
// Check if the image id is valid
if ($imageId !== false) {
// Load the image based on the image id
$imagePath = 'path/to/images/' . $imageId . '.jpg';
// Display the image
echo '<img src="' . $imagePath . '" alt="Image">';
} else {
// Handle invalid input
echo 'Invalid image id';
}
?>