0

I have an error with my photo upload form. I have two fields, one for multiple photos and one for an archive.

<input type="file" name="file[]" multiple="multiple" class="custom-file-input" id="file_upload_gallery" accept="image/*"/>

<input type="file" name="file" class="custom-file-input" id="file_upload" accept="application/zip, application/rar" /> <span class="custom-file-control">

And my PHP script, that throws an error - Invalid argument supplied for foreach()

<?php 
    if (!is_dir($_SERVER['DOCUMENT_ROOT']. '/user_uploads/' . $_POST['user_name'] . '/')){
        mkdir($_SERVER['DOCUMENT_ROOT']. '/user_uploads/' . $_POST['user_name'] . '/');
        foreach($_FILES['file']['name'] as $key=>$filename) {
            print_r($_FILES);
            if(move_uploaded_file($_FILES['file']['tmp_name'][$key], $_SERVER['DOCUMENT_ROOT']. '/user_uploads/' . $_POST['user_name'] . '/' . $filename)) {
                $uploaded[] = $filename; 
            }
        }
        echo json_encode($uploaded);    
    } else {
        foreach($_FILES['file']['name'] as $key=>$filename) {
            print_r($_FILES);
            if(move_uploaded_file($_FILES['file']['tmp_name'][$key], $_SERVER['DOCUMENT_ROOT']. '/user_uploads/' . $_POST['user_name'] . '/' . $filename)) {
                $uploaded[] = $filename; 
            }
        }
        echo json_encode($uploaded);            
    }
?>

Where's a problem? Please help! Thank you!

Cheslav
  • 159
  • 1
  • 2
  • 10
  • Wont work `foreach($_FILES['file[]']` Just do a `print_r($_FILES)` shoudl show you what is in that array – RiggsFolly Apr 30 '17 at 16:31
  • 2
    In your HTML form you realise that the upload input value `file` will overwrite the upload input array values of `file`? It makes the first upload input pointless as things will never be readable – Martin Apr 30 '17 at 16:31

1 Answers1

1

May be problem in the name you use same name file for the two input. and also for this

foreach($_FILES['file[]']['name'] as $key=>$filename) {

you need to write

foreach($_FILES['file']['name'] as $key=>$filename) { // Omit the [] from file
Obaidul Kader
  • 217
  • 1
  • 7
  • 2
    I know you are short of reps, but this is really just a comment. This type of answer attracts downvotes or gets flagged ___I did not DV___ and if that happens you will loose rep points and take longer to get to the 50 reps you need to comment on any question. Until then, stick to questions that are well asked and therefore easily answered without needing clarification. http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead – RiggsFolly Apr 30 '17 at 16:29
  • Thank you very much @RiggsFolly I will follow that from now. – Obaidul Kader Apr 30 '17 at 16:31
  • your answer gave the hint what i was doing wrong in my code cheers – Zain Ul Abidin Jan 05 '21 at 21:01