What are some common pitfalls to avoid when uploading files to a server in PHP?

One common pitfall to avoid when uploading files to a server in PHP is not properly validating the file type. This can lead to security vulnerabilities if malicious files are uploaded. To solve this issue, always validate the file type before allowing the upload to proceed.

// Validate file type before uploading
$allowedFileTypes = ['jpg', 'png', 'gif'];
$uploadedFileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (!in_array($uploadedFileType, $allowedFileTypes)) {
    echo "Invalid file type. Only JPG, PNG, and GIF files are allowed.";
    exit;
}

// Proceed with file upload
// Your file upload code here