1

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

1 Answer 1

1

You shouldn't upload your files like this. Instead, iterate through them with a for or foreach loop 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>';
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for a reply but i have another question, where is the part that uploads the files& How i understand this, if move file is false it gives and error, but how does it upload in case fir condition is false?
The upload happens in the if statement with this line: move_uploaded_file($file['tmp_name'], $target_file . '.' . $type). If the error doesn't show up, it means the file is uploaded. If you read the documentation of move_uploaded_file here then you can see that move_uploaded_file function returns a boolean. False, if the upload was unsuccessful - and therefor the upload didn't happen - and True if the upload was successful. What I did in the if statement was that I'm only catching the error :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.