What are the common pitfalls when trying to include an image in PHP using a variable for the file name?

Common pitfalls when trying to include an image in PHP using a variable for the file name include not properly concatenating the variable with the file path, not checking if the file exists before trying to include it, and not properly sanitizing user input to prevent directory traversal attacks. To solve this issue, make sure to concatenate the variable with the file path using proper string manipulation functions, check if the file exists using file_exists() function, and sanitize the user input using functions like basename().

$filename = $_GET['image']; // Assuming the filename is passed as a query parameter

// Sanitize the input
$filename = basename($filename);

// Define the file path
$imagePath = 'images/' . $filename;

// Check if the file exists before including it
if (file_exists($imagePath)) {
    echo '<img src="' . $imagePath . '" alt="Image">';
} else {
    echo 'Image not found';
}