PHP Contact Form with Add More File Attachment Option

by Vincy. Last modified on July 19th, 2022.

In a contact form, users wish to have different combination of input fields. The contact form may contain input fields like name, email, website, description and lot more. Among those possible contact form fields, the file upload option is common to let the user send attachments with the contact form.

In a previous example, we have seen about sending multiple attachments in the email via PHP contact form by setting “multiple” property in the form’s file input field. In this post, we will see how to create the PHP contact form with the add more attachment option.

In this example, the contact form HTML will have the input fields Name, Email, Subject, Message fields and the file upload with “add more” option. On page load, the form has single file input with “add more attachment”  icon.

php-contact-form-with-add-more-file-attachment-option-output

By clicking this icon, more file input fields are added dynamically to the UI to allow users to choose multiple files with the contact form. On submitting the form, the PHP mail sending script will be executed to send the contact form data with the chosen file attachments to the specified recipient email address.

Contact Form HTML with Add More Attachment Option

In a previous post we saw about storing the information received from a PHP contact form into a database. In this example, we will send the information in email.

This HTML code is used to display a contact form with the Name, Email, Subject, Message and also with the add more attachment option. In this contact form the “add more attachment” is shown next to the file input field. The jQuery function addMoreAttachment() is used to create dynamic file input fields on clicking this function. In this PHP example, all the contact form fields are mandatory except the file attachment fields. The mandatory fields will be validated by using the jQuery form validation script on the form submit.

<!DOCTYPE html>
<html>

<head>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
    type="text/javascript"></script>
<title>PHP Contact Form with Add More File Attachment Option</title>
</head>

<body>
    <h1>PHP Contact Form with Add More File Attachment Option</h1>

    <div class="attachment-form-container">
        <form name="mailForm" id="mailForm" method="post" action=""
            enctype="multipart/form-data"
            onsubmit="return validate()">

            <div class="input-row">
                <label style="padding-top: 20px;">Name</label> <span
                    id="userName-info" class="info"></span><br /> <input
                    type="text" class="input-field" name="userName"
                    id="userName" />
            </div>
            <div class="input-row">
                <label>Email</label> <span id="userEmail-info"
                    class="info"></span><br /> <input type="text"
                    class="input-field" name="userEmail" id="userEmail" />
            </div>
            <div class="input-row">
                <label>Subject</label> <span id="subject-info"
                    class="info"></span><br /> <input type="text"
                    class="input-field" name="subject" id="subject" />
            </div>
            <div class="input-row">
                <label>Message</label> <span id="userMessage-info"
                    class="info"></span><br />
                <textarea name="userMessage" id="userMessage"
                    class="input-field" id="userMessage" cols="60"
                    rows="6"></textarea>
            </div>
            <div class="attachment-row">
                <input type="file" class="input-field"
                    name="attachment[]">

            </div>

            <div onClick="addMoreAttachment();"
                class="icon-add-more-attachemnt"
                title="Add More Attachments">
                <img src="icon-add-more-attachment.png"
                    alt="Add More Attachments">
            </div>
            <div>
                <input type="submit" name="send" class="btn-submit"
                    value="Send" />

                <div id="statusMessage">
                    <?php
                        if (! empty($message)) {
                            ?>
                    <p class='<?php echo $type; ?>Message'>
                        <?php echo $message; ?>
                    </p>
                    <?php
                        }
                        ?>
                </div>
            </div>
        </form>
    </div>

</body>
</html>

And the jQuery functions the validate() to validate the contact form on the submit and the addMoreAttachment() to add dynamic file input option to the UI are shown below. We can add server-side validation and PHP sanitization to handle the contact form data with more security.

<script src="https://code.jquery.com/jquery-2.1.1.min.js"
    type="text/javascript"></script>
<script type="text/javascript">
        function validate() {
            var valid = true;

            $(".info").html("");
            var userName = document.forms["mailForm"]["userName"].value;
            var userEmail = document.forms["mailForm"]["userEmail"].value;
            var subject = document.forms["mailForm"]["subject"].value;
            var userMessage = document.forms["mailForm"]["userMessage"].value;
            
            if (userName == "") {
                $("#userName-info").html("(required)");
                $("#userName").css('background-color', '#FFFFDF');
                valid = false;
            }
            if (userEmail == "") {
                $("#userEmail-info").html("(required)");
                $("#userEmail").css('background-color', '#FFFFDF');
                valid = false;
            }
            if (!userEmail.match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/))
            {
                $("#userEmail-info").html("(invalid)");
                $("#userEmail").css('background-color', '#FFFFDF');
                valid = false;
            }

            if (subject == "") {
                $("#subject-info").html("(required)");
                $("#subject").css('background-color', '#FFFFDF');
                valid = false;
            }
            if (userMessage == "") {
                $("#userMessage-info").html("(required)");
                $("#userMessage").css('background-color', '#FFFFDF');
                valid = false;
            }
            return valid;
        }
        
        function addMoreAttachment() {
            $(".attachment-row:last").clone().insertAfter(".attachment-row:last");
            $(".attachment-row:last").find("input").val("");
        }
</script>

PHP Mail Sending Script with Multiple Attachments

I used PHPMailer to send the contact form email by using Gmail SMTP. In this mail sending script, you have to configure your own SMTP settings. Add the SMTP Username, password and the recipient email address to make the PHP mail script working. In this PHP code, the contact form data are received and used to set the mail header, subject, and body content. The array of uploaded files are iterated in a loop and attached in the mail by using PHPmailer library function AddAttachment() by passing the file tmp_name and name data. In a previous tutorial, we have seen a contact form mail with single attachment.

<?php
if(!empty($_POST["send"])) {
    require_once ('phpmailer/class.phpmailer.php');
    
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;
    $mail->SMTPAuth = TRUE;
    
    $mail->Port = 587;
    
    $mail->Username = "YOUR SMTP USERNAME";
    $mail->Password = "YOUR SMTP PASSWORD";
    
    $mail->Mailer = "smtp";
    
    if (isset($_POST["userEmail"])) {
        $userEmail = $_POST["userEmail"];
    }
    if (isset($_POST["userName"])) {
        $userName = $_POST["userName"];
    }
    if (isset($_POST["subject"])) {
        $subject = $_POST["subject"];
    }
    if (isset($_POST["userMessage"])) {
        $message = $_POST["userMessage"];
    }
    $mail->SetFrom($userEmail, $userName);
    $mail->AddReplyTo($userEmail, $userName);
    $mail->AddAddress("YOUR RECIPIENT EMAIL"); // set recipient email address
    
    $mail->Subject = $subject;
    $mail->WordWrap = 80;
    $mail->MsgHTML($message);
    
    $mail->IsHTML(true);
    
    $mail->SMTPSecure = 'tls';
    $mail->Host = 'smtp.gmail.com';
    
    if (! empty($_FILES['attachment'])) {
        $count = count($_FILES['attachment']['name']);
        if ($count > 0) {
            // Attaching multiple files with the email
            for ($i = 0; $i < $count; $i ++) {
                if (! empty($_FILES["attachment"]["name"])) {
                    
                    $tempFileName = $_FILES["attachment"]["tmp_name"][$i];
                    $fileName = $_FILES["attachment"]["name"][$i];
                    $mail->AddAttachment($tempFileName, $fileName);
                }
            }
        }
    }
    if (! $mail->Send()) {
        $message = "Problem in sending email";
        $type = "error";
    } else {
        $message = "Mail sent successfully";
        $type = "success";
    }
}

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “PHP Contact Form with Add More File Attachment Option”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page