Last modified on July 12th, 2018 by Vincy.

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

If you are looking for a simple secure spam-free contact form in PHP check this linked article. You will get know about the best secure contact form available online and about converting your users to customers.

PHP-Contact-Form-with-Add-More-File-Attachment-Option

In a previous example, we have seen about sending multiple attachments in the email via 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  more  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. 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 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 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 .

<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('-color', '#FFFFDF');
                valid = false;
            }
            if (userEmail == "") {
                $("#userEmail-info").html("(required)");
                $("#userEmail").css('-color', '#FFFFDF');
                valid = false;
            }
            if (!userEmail.match(/^([w-.]+@([w-]+.)+[w-]{2,4})?$/))
            {
                $("#userEmail-info").html("(invalid)");
                $("#userEmail").css('-color', '#FFFFDF');
                valid = false;
            }

            if (subject == "") {
                $("#subject-info").html("(required)");
                $("#subject").css('-color', '#FFFFDF');
                valid = false;
            }
            if (userMessage == "") {
                $("#userMessage-info").html("(required)");
                $("#userMessage").css('-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";
    }
}

PHP Contact Form with Add More File Attachment Output

This screenshow shows the output of the PHP contact form with “add more file attachment” icon. In this screenshot there are two file input fields added dynamically by clicking the add icon next to the last file input option. After executing the mail script the response text displayed in the browser based on the mail sending status.

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

 

Download

This PHP code tutorial was published on July 11, 2018.

↑ Back to Top



Source link
thanks you RSS link
( https://phppot.com/php/php-contact-form-with-add-more-file-attachment-option/)

LEAVE A REPLY

Please enter your comment!
Please enter your name here