Home > Mobile >  PHP Form: different file inputs into array
PHP Form: different file inputs into array

Time:05-30

I try to develop an PHP/HTML form, with multiple file inputs. All these file inputs should be casted into one array, so I can use it so send them as an email attachment.

This is for one file:

// Upload attachment file
        if(!empty($_FILES["attachment"]["name"])){

            // File path config
            $targetDir = "uploads/";
            $fileName = basename($_FILES["attachment"]["name"]);
            $targetFilePath = $targetDir . $fileName;
            $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

            // Allow certain file formats
            $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
            if(in_array($fileType, $allowTypes)){
                // Upload file to the server
                if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
                    $uploadedFile = $targetFilePath;
                    
                }else{
                    $uploadStatus = 0;
                    $statusMsg = "Sorry, there was an error uploading your file.";
                }
            }else{
                $uploadStatus = 0;
                $statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
            }
        }

and that is just for that:

<div >
                    <input type="file" name="attachment" >
                </div>

but I have 2 others from these form groups that should also get uploaded

CodePudding user response:

@kmoser pointed you in the right direction handling multiple file upload with PHP in the comments.

When one or more file type form elements are posted with the square bracket [] indicator at the end of the name, in this case named "attachment", such as:

<input type="file" name="attachment[]" >

...PHP initializes the arrays, similarly to:

$_FILES['attachment']['name'] = [];
$_FILES['attachment']['tmp_name'] = [];
$_FILES['attachment']['size'] = [];
$_FILES['attachment']['type'] = [];

...and for each file uploaded pushes the individual file values to the corresponding array, resulting, for example, in what looks like:

$_FILES['attachment']['name'][0] = "img1.png";
$_FILES['attachment']['name'][1] = "img2.png";
$_FILES['attachment']['name'][2] = "img3.png";

You can loop over any of those arrays, to get the array indexes, and build what array you need to attach the files to an email:

$uploadedFiles = [];
foreach ( $_FILES["attachment"]["name"] as $key => $file ) {
  $name = $_FILES["attachment"]["name"][$key];
  //$tmp_name = $_FILES["attachment"]["tmp_name"][$key];
  //$size = $_FILES["attachment"]["size"][$key];
  //$type = $_FILES["attachment"]["type"][$key];
  $uploadedFiles[] = $targetDir . basename($name);
}

Given form inputs:

<!-- add square brackets after file input name, this works on any form element name and tells PHP to make and array
<div >
  <input type="file" name="attachment[]" >
  <input type="file" name="attachment[]" >
  <input type="file" name="attachment[]" >
</div>

OR a single file input with the multiple attribute:

<div >
  <input type="file" name="attachment[]"  multiple="multiple">
</div>

...submit form to php file containing:

// --> Don't include square brackets with file input name
if(!empty($_FILES["attachment"]["name"])){

// --> instantiate files array
  $uploadedFiles = []; 

  foreach ( $_FILES["attachment"]["name"] as $key => $file ) {
    // File path config
    $targetDir = "uploads/";

// --> use $key to access individual file
    $fileName = basename($_FILES["attachment"]["name"][$key]); 

    $targetFilePath = $targetDir . $fileName;
    $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
    // Allow certain file formats
    $allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
    if(in_array($fileType, $allowTypes)){
        // Upload file to the server
        if(move_uploaded_file($_FILES["attachment"]["tmp_name"][$key], $targetFilePath)){

// --> append file to files array
            $uploadedFiles[] = $targetFilePath; 
            
        }else{
            $uploadStatus = 0;
            $statusMsg = "Sorry, there was an error uploading your file.";
        }
    }else{
        $uploadStatus = 0;
        $statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
    }
  }

// --> attach $uploadedFiles to email
  attachFilesToEmail($uploadedFiles); // (pseudo code)

}

CodePudding user response:

Declare an array in php And where you are adding the file or saving the file in php code, add this line

$array.push($uploadedFile)
  • Related