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

One common pitfall when working with image uploads in PHP is not validating the file type properly, which can lead to security vulnerabilities. To avoid this, always check the file type before allowing the upload to prevent users from uploading malicious files. Another pitfall is not sanitizing the file name, which can lead to directory traversal attacks. Make sure to sanitize the file name to remove any potentially harmful characters.

// Validate file type
$allowed_types = array('jpg', 'jpeg', 'png', 'gif');
$file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_types)) {
    die('Invalid file type. Allowed types are jpg, jpeg, png, gif.');
}

// Sanitize file name
$filename = preg_replace("/[^a-zA-Z0-9.-]/", "", $_FILES['image']['name']);