What are some potential pitfalls to be aware of when using <input type="file"> in PHP for file uploads?
One potential pitfall when using <input type="file"> for file uploads in PHP 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 mitigate this risk, always validate the file type and size on the server side before moving the file to its final destination.
<?php
// Check if file is uploaded
if(isset($_FILES['file'])){
$file = $_FILES['file'];
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if(!in_array($file['type'], $allowedTypes)){
die('Invalid file type. Only JPG, PNG, and GIF files are allowed.');
}
// Validate file size
$maxFileSize = 2 * 1024 * 1024; // 2MB
if($file['size'] > $maxFileSize){
die('File size exceeds the limit of 2MB.');
}
// Move uploaded file to destination folder
move_uploaded_file($file['tmp_name'], 'uploads/' . $file['name']);
echo 'File uploaded successfully.';
}
?>