Home > Mobile >  PHP multiple file upload that allows empty fields
PHP multiple file upload that allows empty fields

Time:04-16

I'm in the process of learning file uploading and PHP, so apologies if I can't describe myself properly.

I'm trying to create a form for uploading up to 5 images. My problem is a logical operator that wouldn't necessitate 4th or 5th image. Currently if I upload 4 images, the program stops uploading at the 3rd image.

if ((move_uploaded_file($_FILES["image1"]["tmp_name"], $target_file.".".$image1FileType)
      && move_uploaded_file($_FILES["image2"]["tmp_name"], $target_file2.".".$image2FileType)
      && move_uploaded_file($_FILES["image3"]["tmp_name"], $target_file3.".".$image3FileType))
      || move_uploaded_file($_FILES["image4"]["tmp_name"], $target_file4.".".$image4FileType)
      || move_uploaded_file($_FILES["image5"]["tmp_name"], $target_file5.".".$image5FileType)
      )

CodePudding user response:

You shouldn't upload your files like this. Instead, iterate through them with a for or foreach cycle and upload them one by one if they are not empty.

foreach($_FILES as $file) {
    if (!isset($file['tmp_name'])) {
        // File is empty so continue with the next file
        continue;
    }

    $nameArray = explode('.', $file['name']);
    $type = end($nameArray);
    $target_file = 'You name it how you want it';

    if (!move_uploaded_file($file['tmp_name'], $target_file . '.' . $type)) {
        echo 'File ' . $file['name'] . ' couldn\'t be uploaded<br>';
    }
}
  • Related