如何将多个文件附加到wordpress中的php表单插件

I have a plugin I am making with a php form that sends an email. Everything in the form is sending the values I need to send, but there is an file attachment area where users can attach multiple files.

The html form (via echo's in the plugin)

function html_form_code() {

    echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
    echo '<div class="row">';
    echo '<div class="col-xs-12 col-md-4">';
    echo '<input class="form-control" type="text" placeholder="Name" label="Name" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" />';
    echo '</div>';
    echo '<div class="col-xs-12 col-md-4">';
    echo '<input class="form-control" type="text" placeholder="company" label="company" name="cf-company" value="' . ( isset( $_POST["cf-company"] ) ? esc_attr( $_POST["cf-company"] ) : '' ) . '" size="40" />';
    echo '</div>';
    echo '<div class="col-xs-12 col-md-4">';
    echo '<input class="form-control" type="text" placeholder="phone" label="phone" name="cf-phone" pattern="[0-9 ]+" value="' . ( isset( $_POST["cf-phone"] ) ? esc_attr( $_POST["cf-phone"] ) : '' ) . '" size="40" />';
    echo '</div>';
    echo '</div>';
    echo '<div class="row">';
    echo '<div class="col-xs-12">';
    echo '<input class="form-control" type="text" placeholder="email" label="email" name="cf-email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" />';
    echo '</div>';
    echo '</div>';
    echo '<div class="row">';
    echo '<div class="col-xs-12">';
    echo '<label for="formDeliverables[]">Select the countries that you have visited:</label><br>';
    echo '<select name="formDeliverables[]">';
    echo '<option value="New Website">New Website</option>';
    echo '<option value="New Web Features">New Web Features</option>';
    echo '<option value="Website Stabilization">Website Stabilization</option>';
    echo '<option value="3rd Party Email Integration">3rd Party Email Integration</option>';
    echo '<option value="Web Virus Removal">Web Virus Removal</option>';
    echo '<option value="Web Security Review">Web Security Review</option>';
    echo '</select>';
    echo '</div>';
    echo '</div>';


    echo '<div class="row checkboxes">';
    echo '<div class="col-sm-12 col-md-6">';
    echo '<label>Copy Writing:</label><br>';
    echo '<input type="checkbox" name="copy[]" value="Copy provided" size="40" /><label for="Copy provided" name="check" class="checks">I will provide copy.</label>';
    echo '<input type="checkbox" name="copy[]" value="Copy needed" size="40" /><label for="Copy needed" name="check" class="checks">I need copy.</label>';
    echo '<input type="checkbox" name="copy[]" value="Not sure about copy" size="40" /><label for="Not sure about copy" name="check" class="checks">I\'m not sure.</label>';
    echo '</div>';


    echo '<div class="col-sm-12 col-md-6">';
    echo '<label>Design Services:</label><br>';
    echo '<input type="checkbox" name="design[]" value="Design provided" size="40" /><label for="Design provided" name="check" class="checks">I will need design services.</label>';
    echo '<input type="checkbox" name="design[]" value="Design needed" size="40" /><label for="Design needed" name="check" class="checks">I will not need design services.</label>';
    echo '<input type="checkbox" name="design[]" value="Not sure about design" size="40" /><label for="Not sure about design" name="check" class="checks">I\'m not sure.</label>';
    echo '</div>';

    echo '<div class="col-sm-12 col-md-6">';
    echo '<label>Illustration:</label><br>';
    echo '<input type="checkbox" name="illustration[]" value="Illustration needed" size="40" /><label for="Illustration needed" name="check" class="checks">I need illustration services.</label>';
    echo '<input type="checkbox" name="illustration[]" value="Illustration not needed" size="40" /><label for="Illustration not needed" name="check" class="checks">I will not need illustration services.</label>';
    echo '<input type="checkbox" name="illustration[]" value="Not sure about illustration" size="40" /><label for="Not sure about illustration" name="check" class="checks">I\'m not sure.</label>';
    echo '</div>';

    echo '<div class="col-sm-12 col-md-6">';
    echo '<label>Photography:</label><br>';
    echo '<input type="checkbox" name="photography[]" value="photography needed" size="40" /><label for="photography needed" name="check" class="checks">I need photography services.</label>';
    echo '<input type="checkbox" name="photography[]" value="photography not needed" size="40" /><label for="photography not needed" name="check" class="checks">I will not need photography services.</label>';
    echo '<input type="checkbox" name="photography[]" value="Not sure about photography" size="40" /><label for="Not sure about photography" name="check" class="checks">I\'m not sure.</label>';
    echo '</div>';

    echo '</div>';


    echo '<div class="container">';
    echo '<div class="row">';
    echo '<label class="control-label">Timelines:</label>';
    echo '</div>';
    echo '<div class="row">';
    echo '<div class="col-sm-6">';
    echo '<input class="form-control datepicker" id="date" name="date_from" placeholder="Select the start date" type="text"/>';
    echo '</div>';

    echo '<div class="col-sm-6">';
    echo '<input class="form-control datepicker" id="date_end" name="date_end" placeholder="Select the end date" type="text"/>';
    echo '</div>';
    echo '</div>';

    echo '<div class="container">';
    echo '<div class="row budget">';
    echo '<div class="col-xs-12">';
    echo '<label for="price">Budget:</label>';
    echo '<div class="double-point-slide">';
    echo '<div id="slider-3"></div>';
    echo '<input type="text" id="price" name="price" style="border:0; color:#000; font-weight:bold;">';
    echo '<input type="text" id="price-two" name="price-two" style="border:0; color:#000; font-weight:bold;">';
    echo '</div>';
    echo '</div>';
    echo '</div>';
    echo '</div>';


    echo '<div class="container table">';
    echo '<div class="row description">';
    echo '<div class="col-xs">  ';  
    echo '<textarea id="projectDescription" placeholder="Describe Your Project" name="cf-message"></textarea>';
    echo '</div>';
    echo '</div>';
    echo '<div class="row add-attachments">';
    echo '<div class="col-xs text-right" >';
    echo '<label><input id="file" type="file" name="file[]" multiple="true"><span>+ Add Inspiration Image</span></label>';
    echo '</div>';
    echo '</div>';
    echo '<div class="row attachments" style="display:none">';
    echo '<div class="col-xs">';
    echo '</div>';
    echo '</div>';
    echo '</div>';


    echo '<div class="container">';
    echo '<div class="row">';
    echo '<div class="col-xs-12">';
    echo '<input type="submit" class="final" name="cf-submitted" value="Submit"/>';
    echo '</div>';
    echo '</div>';
    echo '</div>';



    echo '</form>';


}

Here is the send mail function.

function deliver_mail() {

    // if the submit button is clicked, send the email
    if ( isset( $_POST['cf-submitted'] ) ) {

          // sanitize form values
        $name    = sanitize_text_field( $_POST["cf-name"] );
        $email   = sanitize_email( $_POST["cf-email"] );
        $phone = "Phone: " . sanitize_text_field( $_POST["cf-phone"] );
        $company = "Company: " . sanitize_text_field( $_POST["cf-company"] );
        $deliverablesArr = $_POST["formDeliverables"];
        $deliverables = "Deliverables: " . implode( $deliverablesArr);
        $message = "Message: " . esc_textarea( $_POST["cf-message"] );
        $date_from = $_POST['date_from'];
        $date_end = $_POST['date_end'];
        $date_span = "Timeline: " . $date_from . " - " . $date_end;
        $price = $_POST['price'];
        $price_two = $_POST['price-two'];
        $budget = $price . " - " . $price_two;
        $subject = "Someone needs " . $deliverables . "from a-three.cc!";





        $copy  = 'None';
        if(isset($_POST['copy']) && is_array($_POST['copy']) && count($_POST['copy']) > 0){
            $copy = implode(', ', $_POST['copy']);
        }

        $design  = 'None';
        if(isset($_POST['design']) && is_array($_POST['design']) && count($_POST['design']) > 0){
            $design = implode(', ', $_POST['design']);
        }

        $illustration  = 'None';
        if(isset($_POST['illustration']) && is_array($_POST['illustration']) && count($_POST['illustration']) > 0){
            $illustration = implode(', ', $_POST['illustration']);
        }

        $photography  = 'None';
        if(isset($_POST['photography']) && is_array($_POST['photography']) && count($_POST['photography']) > 0){
            $photography = implode(', ', $_POST['photography']);
        }



        // get the blog administrator's email address
        $to = get_option( 'admin_email' );




        $body = '<html><body>';
        $body .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
        $body .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . $name . "</td></tr>";
        $body .= "<tr><td><strong>Email:</strong> </td><td>" . $email . "</td></tr>";
        $body .= "<tr><td><strong>Company:</strong> </td><td>" . $company . "</td></tr>";
        $body .= "<tr><td><strong>Phone:</strong> </td><td>" . $phone . "</td></tr>";
        $body .= "<tr><td><strong>Deliverables:</strong> </td><td>" . $deliverables . "</td></tr>";
        $body .= "<tr><td style='font-size: 16px'><strong>Services Needed</strong> </td><td></td></tr>";
        $body .= "<tr><td><strong>Copy:</strong> </td><td>" . $copy . "</td></tr>";
        $body .= "<tr><td><strong>Design:</strong> </td><td>" . $design . "</td></tr>";
        $body .= "<tr><td><strong>Illustration:</strong> </td><td>" . $illustration . "</td></tr>";
        $body .= "<tr><td><strong>Photography:</strong> </td><td>" . $photography . "</td></tr>";
        $body .= "<tr><td style='font-size: 16px'><strong>Timeline</strong> </td><td></td></tr>";
        $body .= "<tr><td><strong>Timeline:</strong> </td><td>" . $date_span . "</td></tr>";
        $body .= "<tr><td style='font-size: 16px'><strong>Budget</strong> </td><td></td></tr>";
        $body .= "<tr><td><strong>Budget:</strong> </td><td>" . $budget . "</td></tr>";
        $body .= "<tr><td style='font-size: 16px'><strong>Project Description</strong> </td><td></td></tr>";
        $body .= "<tr><td><strong>Project Description:</strong> </td><td>" . $message . "</td></tr>";


        // If email has been process for sending, display a success message
        if ( wp_mail( $to, $subject, $body ) ) {
            echo '<div>';
            echo '<p>Thanks for contacting us, expect a response soon.</p>';
            echo '</div>';
        } else {
            echo 'An unexpected error occurred';
        }
    }
}

I already have the "file[]" as the name for that field because I assume I need to add each file to an array and then spit it out to the email in a way that can be interpreted. I have tried lots of things but can't quite make this one work.

How do I attach multiple files to a php form in wordpress for emailing?

You miss the last parameter $attachments, it can be an array. You specified that you want to use file[] but I can't see it in the input name.

$attachments = array( WP_CONTENT_DIR . '/uploads/file_to_attach.zip' );

wp_mail( $to, $subject, $message, $headers, $attachments );

Example from wp_mail()

You can use the function move_uploaded_file() to copy the files on the server and unlink() it just after the mail is send.

So I ended up solving it. Thanks to @Benoti for leading me in the right direction. This is the final product with security added to the upload process.

function deliver_mail() {

    // if the submit button is clicked, send the email
    if ( isset( $_POST['cf-submitted'] ) ) {

        $errors = array();

        if (empty($_POST["cf-name"])){
            $nameError = "Name is required";
        } else {
            $name = sanitize_text_field( $_POST["cf-name"] );
        }

          // sanitize form values
        $name = sanitize_text_field( $_POST["cf-name"] );
        $email = sanitize_email( $_POST["cf-email"] );
        $phone = "Phone: " . sanitize_text_field( $_POST["cf-phone"] );
        $company = "Company: " . sanitize_text_field( $_POST["cf-company"] );
        $deliverablesArr = $_POST["formDeliverables"];
        $deliverables = implode( $deliverablesArr);
        $body = esc_textarea( $_POST["cf-body"] );

        $date_from = "None";
        if (empty($_POST["date_from"])){
            $errors[] = 'Please choose a start date.';
        } else {
            $date_from = $_POST['date_from'];
        }

        $date_end = "None";
        if (empty($_POST["date_end"])){
            $errors[] = 'Please choose an end date.';
        } else {
            $date_end = $_POST['date_end'];
        }



        $date_span = $date_from . " - " . $date_end;
        $price = $_POST['price'];
        $price_two = $_POST['price-two'];
        $budget = $price . " - " . $price_two;
        $subject = "Someone needs " . $deliverables . " from a-three.cc!";

        $copy  = 'None';
        if(isset($_POST['copy']) && is_array($_POST['copy']) && count($_POST['copy']) > 0){
            $copy = implode(', ', $_POST['copy']);
        } else {
            $errors[] = 'Please choose if copy is needed.';
        }

        $design  = 'None';
        if(isset($_POST['design']) && is_array($_POST['design']) && count($_POST['design']) > 0){
            $design = implode(', ', $_POST['design']);
        } else {
            $errors[] = 'Please choose if design is needed.';
        }

        $illustration  = 'None';
        if(isset($_POST['illustration']) && is_array($_POST['illustration']) && count($_POST['illustration']) > 0){
            $illustration = implode(', ', $_POST['illustration']);
        } else {
            $errors[] = 'Error: Please choose if Illustration is needed';
        }

        $photography  = 'None';
        if(isset($_POST['photography']) && is_array($_POST['photography']) && count($_POST['photography']) > 0){
            $photography = implode(', ', $_POST['photography']);
        } else {
            $errors[] = 'Please choose if Photography is needed.';
        }

        // get the blog administrator's email address
        $to = get_option( 'admin_email' );

        $message = '<html><body>';
        $message .= '<table rules="all" style="border: 1px solid #666; width: 600px;" cellpadding="10">';
        $message .= "<tr style='background: #eee;'><td style='font-size: 16px' colspan='2'><strong><center>Contact from A-Three</center></strong> </td></tr>";
        $message .= "<tr><td><strong>Name:</strong> </td><td>" . $name . "</td></tr>";
        $message .= "<tr><td><strong>Email:</strong> </td><td>" . $email . "</td></tr>";
        $message .= "<tr><td><strong>Company:</strong> </td><td>" . $company . "</td></tr>";
        $message .= "<tr><td><strong>Phone:</strong> </td><td>" . $phone . "</td></tr>";
        $message .= "<tr><td><strong>Deliverables:</strong> </td><td>" . $deliverables . "</td></tr>";
        $message .= "<tr style='background: #eee;'><td style='font-size: 16px' colspan='2'><strong><center>Services Needed</center></strong> </td></tr>";
        $message .= "<tr><td><strong>Copy:</strong> </td><td>" . $copy . "</td></tr>";
        $message .= "<tr><td><strong>Design:</strong> </td><td>" . $design . "</td></tr>";
        $message .= "<tr><td><strong>Illustration:</strong> </td><td>" . $illustration . "</td></tr>";
        $message .= "<tr><td><strong>Photography:</strong> </td><td>" . $photography . "</td></tr>";
        $message .= "<tr style='background: #eee;'><td style='font-size: 16px' colspan='2'><strong><center>Timeline</center></strong> </td></tr>";
        $message .= "<tr><td><strong>Timeline:</strong> </td><td>" . $date_span . "</td></tr>";
        $message .= "<tr style='background: #eee;'><td style='font-size: 16px' colspan='2'><strong><center>Budget</center></strong> </td></tr>";
        $message .= "<tr><td><strong>Budget:</strong> </td><td>" . $budget . "</td></tr>";
        $message .= "<tr style='background: #eee;'><td style='font-size: 16px' colspan='2'><strong><center>Project Description</center></strong> </td></tr>";
        $message .= "<tr><td><strong>Project Description:</strong> </td><td>" . $body . "</td></tr>";

        $headers = 'From: ' . $email . "
" . 'Reply-To: ' . $email . "
";
        $headers .= "MIME-Version: 1.0
";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1
";

Here is the file uploading section (still the same mail function).

        //file upload function
        $total = count($_FILES['upload']['name']);
        $attachments = "";
        $attachmentString = "";
        $attachmentSet = false;
        //variables for validation
        $maxsize    = 2097152; //just over 2mb
        $whitelist = array(
            'image/jpeg',
            'image/jpg',
            'image/gif',
            'image/png'
        );



        if(file_exists($_FILES['upload']['tmp_name'][0]) || is_uploaded_file($_FILES['upload']['tmp_name'][0])) {

            //hey look the attachment is set!
            $attachmentSet = True;

            // Loop through each file
            for($i=0; $i<$total; $i++) {
              //Get the temp file path
              $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

              //Make sure we have a filepath
              if ($tmpFilePath != ""){
                $uploaddir = 'var/www/uploadsfolderpath/'#changed for security
                wp_mkdir_p( $uploaddir );

                 //rename file
                $orig_name = $_FILES["upload"]["name"][$i];
                $temp = explode(".", $orig_name);
                //give name with original name added by user plus hash random value
                $newfilename = array_values($temp)[0] . md5(array_values($temp)[0]) . '.' . end($temp);

                //variables per each iteration
                //Setup our new file path
                $newFilePath = $uploaddir . $newfilename; //renamed file added to new file path
                $file_type = $_FILES['upload']['type'][$i]; //returns the mimetype
                $imageinfo = getimagesize($_FILES['upload']['tmp_name'][$i]);//returns size of image
                $fileName = strtolower($_FILES['upload']['name'][$i]);
                $upload_extension =  explode(".", $fileName);
                $upload_extension = end($upload_extension);//gets just the extension

                #check for appropriate size with php.ini
                $POST_MAX_SIZE = ini_get('post_max_size');
                $mul = substr($POST_MAX_SIZE, -1);
                $mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1)));
                if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) $error = true; 
                $max_file_size_in_bytes = 2140907;               // 2MB in bytes
                if(count($errors) === 0)
                {
                    #restrict the limit
                    $file_size = @filesize($tmpFilePath);
                    if (!$file_size || $file_size > $max_file_size_in_bytes) {
                        $errors[] = 'File too large. File must be less than 2 GB.'; 
                    }
                }
                else
                {
                    $errors[] = 'File too large. File must be less than 2 GB.';
                }

                //check if isn't a type and if has an image size
                if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/png' && $imageinfo['mime'] != 'image/jpeg' && isset($imageinfo)) 
                {
                    $errors[] = 'Invalid file type. Only JPG, GIF and PNG types are accepted.';
                }
                //file type verficatio
                if(!in_array($file_type, $whitelist) && !empty($_FILES["upload"]["type"])) {
                    $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
                }



                //all conditions passed, upload files!
                if(count($errors) === 0) {
                     //Upload the file into the temp dir
                    if(move_uploaded_file($tmpFilePath, $newFilePath)) {
                    chmod($newFilePath, 0644);
                    $attachments[$i] = $newFilePath;
                    //make string for sending to email
                    $attachmentString[$i] = $newFilePath;
                    $headers .= "Content-Disposition: attachment; filename = \"" . $attachmentString[$i] . "\"

";
                    }
                }
              }
            }//end of loop
        }

        // If email has been process for sending, display a success message
        if(count($errors) === 0) {
            if ( wp_mail( $to, $subject, $message, $headers, $attachments ) ) {
            echo '<div  class="success"><p>Success! Thanks for contacting us, expect a response soon.</p></div>';

                if ($attachmentSet) {
                    //clean up your temp files after sending
                    foreach($attachments as $att) {
                        @unlink($att);
                    };
                }
            } 
        }
        else {
            echo '<div class="error">';
            foreach($errors as $error) {
                echo '<p>' .$error . '</p>';
                }
            echo '</div>';
        }



    }
}

Suggestions welcome as this is my first time building something like this with php :)