PHP File Upload: Ensuring File Type and Size Restrictions
In PHP, handling file uploads often requires verifying file type and size restrictions. The code snippet provided attempts to validate both criteria but encounters issues. Let's delve into the code and identify the errors.
//check file extension and size
$resume = ($_FILES['resume']['name']);
$reference = ($_FILES['reference']['name']);
$ext = strrchr($resume, ".");
$ext1 = strrchr($reference, ".");
This code captures the filename and extension for both files. However, the subsequent validation logic is flawed:
if (!(
($_FILES["resume"]["type"] == "application/doc")
|| ($_FILES["resume"]["type"] == "application/docx")
|| ($_FILES["resume"]["type"] == "application/pdf")
&& (($_FILES["reference"]["type"] == "application/doc")
|| ($_FILES["reference"]["type"] == "application/docx")
|| ($_FILES["reference"]["type"] == "application/pdf"))
&& (($ext == ".pdf") || ($ext == ".doc") || ($ext == ".docx"))
&& (($ext1 == ".pdf") || ($ext1 == ".doc") || ($ext1 == ".docx"))
&& ($_FILES["resume"]["size"] The code fails to use the correct logic for validating file types. Instead of checking the MIME type, it relies on the filename extension, which is unreliable. Additionally, the size validation is not applied to both files.
To rectify these issues, here's a revised code snippet that uses MIME types and correctly checks both file sizes:
function allowed_file() {
$allowed = array('application/doc', 'application/pdf', 'application/docx');
if (in_array($_FILES['resume']['type'], $allowed) && in_array($_FILES['reference']['type'], $allowed)) {
if ($_FILES["resume"]["size"] This code first checks if the files' MIME types are included in the allowed list. If so, it then verifies if both file sizes are within the specified limit. This ensures that only allowed file types and sizes are accepted for upload.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3