What potential pitfalls should be avoided when working with images in PHP?

When working with images in PHP, it is important to avoid potential security vulnerabilities such as allowing users to upload malicious files or executing arbitrary code. To prevent this, always validate and sanitize user input before processing images. Additionally, be mindful of file permissions and ensure that only necessary files are accessible.

// Example of validating and sanitizing user input before processing images
$allowedFormats = ['jpg', 'jpeg', 'png'];
$uploadDir = 'uploads/';

if(isset($_FILES['image'])){
    $image = $_FILES['image'];
    
    $fileName = $image['name'];
    $fileTmpName = $image['tmp_name'];
    $fileSize = $image['size'];
    $fileError = $image['error'];
    
    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    
    if(in_array($fileExt, $allowedFormats)){
        $newFileName = uniqid('', true) . "." . $fileExt;
        $uploadPath = $uploadDir . $newFileName;
        
        move_uploaded_file($fileTmpName, $uploadPath);
        echo "Image uploaded successfully!";
    } else {
        echo "Invalid file format. Please upload a JPG or PNG file.";
    }
}