What are some potential pitfalls when using PHP to handle file uploads?
One potential pitfall when handling file uploads in PHP is not properly validating the file type and size. This can lead to security vulnerabilities such as allowing users to upload malicious files or overwhelming the server with large files. To mitigate this risk, always validate the file type and size before moving the uploaded file to the server.
// Validate file type and size before moving the uploaded file
$allowedFileTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 5 * 1024 * 1024; // 5MB
if (!in_array($_FILES['file']['type'], $allowedFileTypes)) {
die('Invalid file type. Only JPEG and PNG files are allowed.');
}
if ($_FILES['file']['size'] > $maxFileSize) {
die('File size is too large. Maximum file size is 5MB.');
}
// Move the uploaded file to the server
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
Related questions
-
SimpleXML Xpath queries debugging
-
class method variable call
-
PHP script differentiate