What potential pitfalls should be considered when implementing a dynamic image upload feature in PHP?

Potential pitfalls to consider when implementing a dynamic image upload feature in PHP include security vulnerabilities such as file upload attacks, server overload due to large file uploads, and insufficient validation leading to potential data loss or corruption. To mitigate these risks, it is important to implement proper file type validation, limit the file size, sanitize file names, and store uploaded files in a secure location outside of the web root directory.

// Check file type and size before uploading
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if (in_array($_FILES['image']['type'], $allowedTypes) && $_FILES['image']['size'] <= $maxFileSize) {
    // Sanitize file name
    $fileName = strtolower(preg_replace("/[^a-zA-Z0-9.]/", "", $_FILES['image']['name']));
    
    // Move uploaded file to a secure location
    move_uploaded_file($_FILES['image']['tmp_name'], '/path/to/uploads/' . $fileName);
} else {
    echo 'Invalid file type or size.';
}