0

I am running into a scenario that I cannot get more than one file to upload. If I add more than one file, only the last one will send through.

I know an array is needed to be sent and then looped through, so I changed the name of my input to include [] and then tried changing the public function upload. Below you will see the original version of the fileUpload class and then the my attempted updated version.

Here is the original version of the part of my code to get the files moved:

class fileUpload
{
    public function __construct()
    {}
    public function upload() {

        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            return 0;
// if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
                return basename($_FILES["uploadedFile"]["name"]);
            } else {
                return 0;
            }
        }
    }
}

Here is the updated version of fileUpload.php in an attempt to loop through the array.

class fileUpload
{

    public function __construct()
    {}
    public function upload(&$file_post) {

        $file_ary = array();
        $file_count = count($file_post['name']);
        $file_keys = array_keys($file_post);

        for ($index = 0; $index<$file_count; $index++) {
            foreach ($file_keys as $key) {
                $file_ary[$index][$key] = $file_post[$key][$index];
            }
        }
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            return 0;
// if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
                return basename($_FILES["uploadedFile"]["name"]);
            } else {
                return 0;
            }
        }
    }
}

Doing this, I received the following errors:

Notice: Array to string conversion in /php/sharePhotoSend.php on line 30

Fatal error: Uncaught ArgumentCountError: Too few arguments to function fileUpload::upload(), 0 passed in /php/sharePhotoSend.php on line 73 and exactly 1 expected in /php/fileUpload.php:8 Stack trace:

0 /php/sharePhotoSend.php(73): fileUpload->upload()

1 {main} thrown in /php/fileUpload.php on line 8

Here are the lines being referenced:

fileUpload.php Line 8 - public function upload(&$file_post) {

sharePhotoSend.php Line 30 - $projectSubmission_stmt->execute(array($first_name, $last_name, $email, $phone, $company, $details, $fileNameInsert));

Line 73 - $filename = $fu->upload(); Which line 73 is a part of this:

    if (!empty($_FILES['uploadedFile']['name']) && $_FILES['uploadedFile']['error'] != 4) {
            $fu = new fileUpload();
            $filename = $fu->upload();
            $template = str_replace("{filename}", "A file was uploaded. You can download the file from: <a href='https://mbkit.com/php/uploads/{$filename}'>{$filename}</a>", $template);
    //            print_r($template);
    //              echo "Should be working and hitting the if condition";
            if ( !$filename ) {
                echo json_encode(['status_code' => 500,
                    'message' => "We were not able to upload your file at this time."]);
            }
            clearstatcache();

UPDATE - New fileUpload class:

<?php

class fileUpload
{

    public function __construct()
    {}
    public function upload() {

        $file_ary = array();
        $file_count = count($_FILES['uploadedFile']['name']);
        //$file_count = count($_FILES($file_post['name']));

        for ($i = 0; $i<$file_count; $i++) {
//          echo $file['uploadedFile']['name'][$index] . "\n";

            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"][$i]);
            $uploadOk = 1;
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));        

            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                return 0;
    // if everything is ok, try to upload file
            } else {
                if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"][$i], $target_file)) {
                    return basename($_FILES["uploadedFile"]["name"][$i]);
                } else {
                    return 0;
                }
            }
        }
    }
}

Communication Class - this sends the attachments

if (!empty($file) && !$recipient && count($file['uploadedFile']['name']) > 1) {

                $f = new ZipArchive();
                $zip = $f->open('uploads/' . $file['uploadedFile']['name'][0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
                if ($zip) {
                    for ($index = 0; $index < count($file['uploadedFile']['name']); $index++) {
//                        echo $file['uploadedFile']['name'][$index] . "\n";
                        $f->addFile($file['uploadedFile']['tmp_name'][$index], $file['uploadedFile']['name'][$index]);
                    }
                    $f->close();

                    $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name'][0]}.zip",
                        pathinfo("uploads/{$file['uploadedFile']['name'][0]}.zip", PATHINFO_EXTENSION),
                        $file['uploadedFile']['name'][0] . ".zip");
                } else {
                    throw new Exception("Could not zip the files.");
                }

            } 
Paul
  • 3,348
  • 5
  • 32
  • 76
  • Possible duplicate of [Multiple file upload in php](https://stackoverflow.com/questions/2704314/multiple-file-upload-in-php) – zbee Aug 02 '19 at 19:31
  • @zbee Not really. I am showing specific cases. My question was not generic...... – Paul Aug 02 '19 at 19:32
  • Regarding your fatal error, the new version of `fileUpload` requires the specific file in `$_FILES` to be passed in, and you're not currently providing that parameter. – zbee Aug 02 '19 at 19:33
  • @zbee Would I put that in my count variable? Like this: `$file_count = count($_FILES($file_post['name']));` – Paul Aug 02 '19 at 19:35
  • I am still getting the same errors based on changing the count variable to what I put above. – Paul Aug 02 '19 at 19:37
  • No, as in you need to provide `fileUpload`'s `upload` method with a parameter, and in the line `$filename = $fu->upload();` you are providing no parameter. – zbee Aug 02 '19 at 19:40
  • Are you saying to add `&$file_post` to `$filename = $fu->upload();`? So `$filename = $fu->upload(&$file_post);` ? – Paul Aug 02 '19 at 19:42
  • Yes, essentially, but the class method is simply expecting `$_FILES["uploadedFile"]` to be passed in - or so it seems. – zbee Aug 02 '19 at 19:44
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/197406/discussion-between-zbee-and-paul). – zbee Aug 02 '19 at 19:44
  • @zbee My server for some reason blocks the chat. – Paul Aug 02 '19 at 19:44
  • Should I just remove this line of code: `$file_ary[$index][$key] = $file_post[$key][$index];` and take out the parameter being passed in the function `&$file_post`. Then put the rest of the code into my foreach loop? – Paul Aug 02 '19 at 19:47
  • Why is `$file_post` a reference parameter? You never modify it in the function, so there's no need to pass it by reference. – Barmar Aug 02 '19 at 20:03
  • The function can just use `$_FILES` in place of `$file_post`. – Barmar Aug 02 '19 at 20:05
  • @Barmar I took that out and rewrote the function. See the update. The only error I get now is referring to my communication class query - I can deal with that later. However, my Communication class, which sends the attachments via email, is not sending the array of files in the zip. All I get is the last file uploaded again. I updated my question with the new code. See where it says update. – Paul Aug 02 '19 at 20:10

0 Answers0