What are some common mistakes to avoid when working with file uploads in PHP?
One common mistake to avoid when working with file uploads in PHP is not checking the file type before allowing the upload. This can lead to security vulnerabilities, as malicious files could be uploaded to the server. To solve this, always validate the file type before moving the uploaded file to the desired location.
// Check file type before allowing upload
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
echo 'Invalid file type. Please upload a JPEG, PNG, or GIF file.';
exit;
}
// Move uploaded file to desired location
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);