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.
<code class="php">//check file extension and size $resume = ($_FILES['resume']['name']); $reference = ($_FILES['reference']['name']); $ext = strrchr($resume, "."); $ext1 = strrchr($reference, ".");</code>
This code captures the filename and extension for both files. However, the subsequent validation logic is flawed:
<code class="php">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"] < 400000) //accept upto 500 kb && ($_FILES["reference"]["size"] < 400000) )) { //stop user } else { //allow files to upload }</code>
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:
<code class="php">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"] < 400000 && $_FILES["reference"]["size"] < 400000) { // Begin file upload here... } } }</code>
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.
The above is the detailed content of Why Is My PHP File Upload Validation Code Not Working Correctly?. For more information, please follow other related articles on the PHP Chinese website!