What are some common pitfalls to avoid when working with image directories in PHP?

One common pitfall when working with image directories in PHP is not properly sanitizing user input, which can lead to security vulnerabilities such as directory traversal attacks. To avoid this, always validate and sanitize user input before using it to access image files. Additionally, make sure to handle file uploads securely to prevent malicious files from being uploaded to the server.

// Example of sanitizing user input before accessing image files
$directory = '/path/to/images/';
$image = isset($_GET['image']) ? $_GET['image'] : 'default.jpg';
$image = basename($image); // Sanitize user input to prevent directory traversal attacks

// Example of securely handling file uploads
$uploadDirectory = '/path/to/uploads/';
$allowedExtensions = ['jpg', 'png', 'gif'];
if(isset($_FILES['image'])) {
    $fileExtension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    if(in_array($fileExtension, $allowedExtensions)) {
        move_uploaded_file($_FILES['image']['tmp_name'], $uploadDirectory . $_FILES['image']['name']);
    } else {
        echo 'Invalid file type. Allowed extensions are jpg, png, gif.';
    }
}