Home > Back-end >  Validate input file
Validate input file

Time:09-25

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]);

        }

CodePudding user response:

Consider the following.

<?php    
$message = array();
foreach($_FILES, $k => $f){
  if(empty($f)){
    array_push($message, array(
      "error" => true,
      "message" => "The document type is incorrect. Please select .excel, .word, .jpg, .png"
     ));
  } else {
    move_uploaded_file($f['tmp_name'], $_SERVER["DOCUMENT_ROOT"] . 'mdh/files/' . $f['name']);
    array_push($message, array(
      "error" => false,
      "message" => "File Uploaded: " . $f['name'] . ", Type: " . $f['type'];
    ));
  }
}
if(count($message)){
  echo json_encode($message);
}
?>

This will iterate each File and check if it is Empty. Also watch out for minor typos like: ['name] versus ['name'].

  • Related