What are common pitfalls when using PHP for image uploads?

One common pitfall when using PHP for image uploads is not validating the uploaded file properly, which can lead to security vulnerabilities such as allowing malicious files to be uploaded. To solve this, always validate the file type and size before moving it to the server.

// Validate file type and size before moving it to the server
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
$max_size = 5 * 1024 * 1024; // 5MB

if (in_array($_FILES['file']['type'], $allowed_types) && $_FILES['file']['size'] <= $max_size) {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    echo 'File uploaded successfully.';
} else {
    echo 'Invalid file type or size.';
}