What are the common mistakes or oversights that developers make when attempting file uploads in PHP, and how can they be avoided?
Common mistakes when attempting file uploads in PHP include not checking if the file was successfully uploaded, not validating the file type or size, and not securing the file upload directory. To avoid these issues, always check if the file was uploaded using `is_uploaded_file()`, validate the file type and size using `$_FILES['file']['type']` and `$_FILES['file']['size']`, and move the uploaded file to a secure directory using `move_uploaded_file()`.
if(isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
$allowedTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 1048576; // 1MB
if(in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize) {
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo "File uploaded successfully!";
} else {
echo "Error uploading file.";
}
} else {
echo "Invalid file type or size.";
}
}