John Davidson

php - Validate input file

0 comments
Message:


I have to validate 3 input file, any idea or guidance to improve my code ?


I was thinking to validate it using jquery


if (empty($_FILES['docmuent_1']) && !isset($_FILES('document_2']) && !isset($_FILES('document_3']) {
echo json_encode(array(
'error' => true,
'message' => 'The document is incorrect, Please select .excel, .word, .jpg, .png'
));
} else {
move_uploaded_file($_FILES['document_1']['tmp_name'], $_SERVER["DOCUMENT_ROOT"] . 'mdh/files/ . $_FILES['document_1'] ['name]);
}

if (empty($_FILES['document2']) && !isset($_FILES['document_3]) ) {
echo json_encode(array(
'error' => true,
'message' => 'The document is incorrect, Please select .excel, .word, .jpg, .png'
));
} else {
move_uploaded_file($_FILES['document_2']['tmp_name'], $_SERVER["DOCUMENT_ROOT"] . 'mdh/files/ . $_FILES['document_2'] ['name]);

}


My Answer:
{
if (empty($_FILES['document_1']) || empty($_FILES['document_2']) || empty($_FILES['document_3'])) {
echo "Please upload all 3 documents.";
} else {
// Validate file types and sizes
$allowedTypes = ['pdf', 'doc', 'docx'];
$maxSize = 5 * 1024 * 1024; // 5MB

foreach ($_FILES as $file) {
$fileType = pathinfo($file['name'], PATHINFO_EXTENSION);
$fileSize = $file['size'];

if (!in_array($fileType, $allowedTypes)) {
echo "Invalid file type for " . $file['name'];
} elseif ($fileSize > $maxSize) {
echo "File size exceeds limit for " . $file['name'];
} else {
// File is valid, do something with it
}
}
}
}

Rate this post

3 of 5 based on 9891 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us