What potential pitfalls should be avoided when displaying images from a folder in PHP?
One potential pitfall to avoid when displaying images from a folder in PHP is the risk of allowing users to access sensitive files or execute malicious scripts. To prevent this, it is important to sanitize user input and validate the file path before displaying the images. Additionally, it is recommended to store the images outside of the web root directory to prevent direct access.
<?php
$folder = "images/";
$allowed_extensions = array("jpg", "jpeg", "png", "gif");
// Sanitize and validate the file path
$image = isset($_GET['image']) ? $_GET['image'] : '';
$image_path = realpath($folder . $image);
if (strpos($image_path, $folder) !== 0 || !in_array(pathinfo($image_path, PATHINFO_EXTENSION), $allowed_extensions)) {
die("Invalid image path");
}
// Display the image
header("Content-Type: image/jpeg");
readfile($image_path);
?>
Keywords
Related Questions
- What are the best practices for handling $_GET and $_POST variables in PHP to ensure data integrity and security?
- How can the code for storing user login information, including IP addresses, be optimized for performance and security in PHP?
- What are the common pitfalls when trying to incorporate JavaScript into PHP code?