What are common pitfalls when using file upload in PHP scripts?

One common pitfall when using file upload in PHP scripts is not properly validating the file type and size before processing the upload. This can lead to security vulnerabilities such as allowing malicious files to be uploaded to the server. To solve this issue, always validate the file type and size before moving the uploaded file to its destination directory.

// Validate file type and size before moving the uploaded file
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 1048576; // 1MB

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