1. Computer problem? Tech Support Guy is completely free -- paid for by advertisers and donations. Click here to join today! If you're new to Tech Support Guy, we highly recommend that you visit our Guide for New Members.

Contact form feedback

Discussion in 'Web Design & Development' started by EspressoBean, Jun 12, 2018.

Thread Status:
Not open for further replies.
Advertisement
  1. EspressoBean

    EspressoBean Thread Starter

    Joined:
    Feb 29, 2016
    Messages:
    264
    So I have created a contact form that originally did not have any mechanism in sending out the email with whatever the user inputted in the fields. I have added it in here along with ReCaptcha check. I would like to get some feedback on the code, especially that I am looking to upgrading the email body to send out emails that are styled and look better.

    PHP:
        <?php
        $yourEmail 
    "[email protected]"// <== Your Email
        
    $secret 'LALALALAALALALALALALA'// <==Your recaptcha Privte Key
        
    $errors         = array();      // array to hold validation errors
        
    $data             = array();         // array to pass back data
      
        // validate the variables ======================================================
            // if any of these variables don't exist, add an error to our $errors array
      
            // ---------------------Start the recaptcha ------------------------------------//
            
    if(isset($_POST['g-recaptcha-response']) && ($_POST['g-recaptcha-response'])){
                            
    session_start();
                    
    $ip $_SERVER['REMOTE_ADDR'];
                    
    $captcha $_POST['g-recaptcha-response'];
                    
    $response file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip=$ip");
                    
    $result json_decode($response,TRUE);
                            if(
    $result['success'] == 1){
                                    
    $_SESSION['result'] = $result['success'];
                                    }
            
    // --------------------End Of the Captcha Check------------------------- //
      
            
    if (empty($_POST['name']))
                
    $errors['name'] = 'Name is required.';
      
            if (empty(
    $_POST['email']))
                
    $errors['email'] = 'Email is required.';
      
            if (empty(
    $_POST['phone']))
                
    $errors['phone'] = 'Phone is required.';
      
                
    // ---------------------Start the recaptcha ------------------------------------//
      
                
    if(!isset($_SESSION['result']) || $_SESSION['result'] == 0){
                        
    $formerrors[] =  'Captcha Error';
                }
      
                
    // --------------------End Of the Captcha Check------------------------- //
      
        // return a response ===========================================================
      
            // if there are any errors in our errors array, return a success boolean of false
            
    if ( ! empty($errors)) {
      
                
    // if there are items in our errors array, return those errors
                
    $data['success'] = false;
                
    $data['errors']  = $errors;
            } else {
      
                
    // if there are no errors process our form, then return a message
      
                // DO ALL YOUR FORM PROCESSING HERE
                // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
      
                // show a message of success and provide a true success variable
                
    $data['success'] = true;
                
    $data['message'] = 'Success!';
            }
      
            
    // return all our data to an AJAX call
            
    echo json_encode($data);
      
            
    //Start of Sending Email
            
    $to $yourEmail;    // Email to receive contacts
            
    $from $email;
            
    $subject 'Contact Form Email : ' $title;
            
    $message '<style>
                                    body{background-color:#fefefe}
                                    .email-style {padding: 30px;background: #fafafa;font-size: 18px;border: 1px solid #ddd;width: 60%;margin: auto;}
                                    p {padding: 15px 0px;}
                                    </style>
      
                                    <div class="email-style"><p> '
    .$title '</p>
      
                                    <p>Contact Full Name : '
    .$name ' </p>
      
                                    <p>Contact Email : '
    .$email ' </p>
      
                                    <p>Contact Phone Number : '
    .$phone '</p>
      
                                    <p>Message : '
    .$message ' </p>
      
                                    <p>Cheers,</p>
                                    <p>'
    .$name.' Via Contact Form</p></div>';
      
            
    $headers "From: $from\n";
            
    $headers .= "MIME-Version: 1.0\n";
            
    $headers .= "Content-type: text/html; charset=iso-8859-1\n";
                if( 
    mail($to$message$headers) ){
                            echo 
    "sent";
                            
    session_unset();
                            
    session_destroy();
                        } else {
                                        echo 
    "The server failed to send the message. Please try again later.";
                                    }
                                }
        
    ?>
     
  2. JiminSA

    JiminSA

    Joined:
    Dec 15, 2011
    Messages:
    3,220
    The thing to be aware of with emaiils is that most email handlers do not cope with positional styling and therefore it's best to use tables!
    You might also want to consider an image or two to improve the look;)
    Here's an example ...
    PHP:
     //******************************************** COLLECT FORM DATA
            
    $name $_POST['fullName'];
            
    $email $_POST['email'];
            
    $phone $_POST['phone'];
            
    $adults $_POST['adults'];
            
    $children $_POST['children'];
            
    $infants $_POST['infants'];
            
    $dogs $_POST['dogs'];
            
    $msg $_POST['comments'];
            
    $format "l jS F Y";
            
    $from date($format$_POST['day_in']);
            
    $to date($format$_POST['day_out']);
            
    $nights $_POST['nights'];
    //******************************************** EMAIL SITE OWNER 
            
    $subject "Website Booking Enquiry Form submission";
            
    $headers "From: [email protected] \r\n";
            
    $headers .= "MIME-Version: 1.0\r\n";
            
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
            
    $line1 "";
            
    $line1 .= "<tr><td>$name has just filled out the Booking Enquiry form.</td></tr>";
            if(
    $dogs)
            {
                
    $line2 "<tr><td>They will be bringing $dogs dog(s).</td></tr>";
            }
            else
            {
                
    $line2 "<tr><td>They will not be bringing any dogs.</td></tr>";
            }
            
    $body "<html><body><table style=\"background-color: #fff; color:#00f; font-family: Trebuchet MS, Arial, Helvetica, sans-serif; font-size:20px\" cellpadding=\"10\" >
            <tr><td><a href=''><img src='http://the_website.com/images/small_logo.png' align='left' alt=''/></a></td><tr>
            <tr><td>Dear 'Site Owner's name',</td></tr> 
    $line1 <tr><td>Their email address is $email ...</td></tr>
            <tr><td>Their phone number is 
    $phone ...</td></tr>
            <tr><td>
    $adults adult(s), $children child(ren) and $infants infant(s) want to stay from ...<br />$from until $to - $nights nights ...</td></tr>
            
    $line2
            <tr><td>Here is what they have to say:</td></tr>
            <tr><td>
    $msg</td></tr>
            <tr><td>Regards,</td></tr>
            <tr><td>Your Website</td></tr></table></body></html>"
    ;

            
    $to "[email protected]";
            
    mail($to$subject$body$headers);
     
  3. EspressoBean

    EspressoBean Thread Starter

    Joined:
    Feb 29, 2016
    Messages:
    264
    @JiminSA maybe, I am still looking into figuring out the format to go with when sending emails. Based on your best knowledge, will the email be sent?
     
  4. JiminSA

    JiminSA

    Joined:
    Dec 15, 2011
    Messages:
    3,220
    In a word, no :(
    You have unassigned variables $title, $name, $email, $phone and probably $message - you have included $message as one of the components of $message. Also you are not sending the email with a subject.
    Assign your posted variables and ...
    change '$message =' to '$body =' and ...
    your mail command from 'if( mail($to, $message, $headers) )' to 'if( mail($to, $subject, $body, $headers) )' and it should send quite happily;)
     
  5. EspressoBean

    EspressoBean Thread Starter

    Joined:
    Feb 29, 2016
    Messages:
    264
    So like this?

    PHP:
    <?php
    $yourEmail 
    "[email protected]"// <== Your Email
    $secret 'LALALALAALALALALALALA'// <==Your recaptcha Privte Key
    $errors         = array();      // array to hold validation errors
    $data             = array();         // array to pass back data

    // validate the variables ======================================================
        // if any of these variables don't exist, add an error to our $errors array

        // ---------------------Start the recaptcha ------------------------------------//
        
    if(isset($_POST['g-recaptcha-response']) && ($_POST['g-recaptcha-response'])){
                        
    session_start();
                
    $ip $_SERVER['REMOTE_ADDR'];
                
    $captcha $_POST['g-recaptcha-response'];
                
    $response file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remoteip=$ip");
                
    $result json_decode($response,TRUE);
                        if(
    $result['success'] == 1){
                                
    $_SESSION['result'] = $result['success'];
                                }
        
    // --------------------End Of the Captcha Check------------------------- //

        
    if (empty($_POST['name']))
            
    $errors['name'] = 'Name is required.';

        if (empty(
    $_POST['email']))
            
    $errors['email'] = 'Email is required.';

        if (empty(
    $_POST['phone']))
            
    $errors['phone'] = 'Phone is required.';

        if (empty(
    $_POST['message']))
            
    $errors['message'] = 'Message is required.';

            
    // ---------------------Start the recaptcha ------------------------------------//

            
    if(!isset($_SESSION['result']) || $_SESSION['result'] == 0){
                     
    $errors[] =  'Captcha Error';
            }

            
    // --------------------End Of the Captcha Check------------------------- //

    // return a response ===========================================================

        // if there are any errors in our errors array, return a success boolean of false
        
    if ( ! empty($errors)) {

            
    // if there are items in our errors array, return those errors
            
    $data['success'] = false;
            
    $data['errors']  = $errors;
        } else {

            
    // if there are no errors process our form, then return a message

            // DO ALL YOUR FORM PROCESSING HERE
            // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

            // show a message of success and provide a true success variable
            
    $data['success'] = true;
            
    $data['message'] = 'Success!';
        }

        
    // return all our data to an AJAX call
        
    echo json_encode($data);

        
    //Start of Sending Email
        
    $to $yourEmail;    // Email to receive contacts
        
    $from $email;
        
    $subject 'Contact Form Email : ' $subject;
        
    $message '<style>
                                body{background-color:#fefefe}
                                .email-style {padding: 30px;background: #fafafa;font-size: 18px;border: 1px solid #ddd;width: 60%;margin: auto;}
                                p {padding: 15px 0px;}
                                </style>

                                <div class="email-style"><p> '
    .subject '</p>

                                <p>Contact Full Name : '
    .$name ' </p>

                                <p>Contact Email : '
    .$email ' </p>

                                <p>Contact Phone Number : '
    .$phone '</p>

                                <p>Message : '
    .$message ' </p>

                                <p>Cheers,</p>
                                <p>'
    .$name.' Via Contact Form</p></div>';

        
    $headers "From: $from\n";
        
    $headers .= "MIME-Version: 1.0\n";
        
    $headers .= "Content-type: text/html; charset=iso-8859-1\n";
             if( 
    mail($to$subject$body$headers) ){
                        echo 
    "sent";
                        
    session_unset();
                        
    session_destroy();
                    } else {
                                     echo 
    "The server failed to send the message. Please try again later.";
                                }
                            }
    ?>
     
  6. EspressoBean

    EspressoBean Thread Starter

    Joined:
    Feb 29, 2016
    Messages:
    264
    Here is my new attempt, specifically regarding the email sent part.

    PHP:
    $subject 'New Contact From Website Name';

    //Header Content
    $headers "From: " strip_tags($_POST['emailAddress']) . "\r\n";
    $headers .= "Reply-To: "strip_tags($_POST['emailAddress']) . "\r\n";
    $headers .= "CC: [email protected]\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    //Message Content
    $message '<html><body>';
    $message .= '<h1>Hello, World!</h1>';
    $message .= '</body></html>';
    $message '<html><body>';
    $message .= '<img src="//css-tricks.com/examples/WebsiteChangeRequestForm/images/wcrf-header.png" alt="Website Change Request" />';
    $message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
    $message .= "<tr style='background: #eee;'><td><strong>First Name:</strong> </td><td>" strip_tags($_POST['firstName']) . "</td></tr>";
    $message .= "<tr style='background: #eee;'><td><strong>Last Name:</strong> </td><td>" strip_tags($_POST['lastName']) . "</td></tr>";
    $message .= "<tr><td><strong>Email Address:</strong> </td><td>" strip_tags($_POST['emailAddress']) . "</td></tr>";
    $message .= "<tr><td><strong>Phone Number:</strong> </td><td>" strip_tags($_POST['phoneNumber']) . "</td></tr>";
    $message .= "<tr><td><strong>Subject:</strong> </td><td>" strip_tags($_POST['subject']) . "</td></tr>";
    $message .= "<tr><td><strong>Message:</strong> </td><td>" $_POST['message'] . "</td></tr>";
    $message .= "</table>";
    $message .= "</body></html>";

    // Send email
    if(mail($to$subject$body$headers)):
        
    $successMsg 'Email has sent successfully.';
    else:
        
    $errorMsg 'Email sending fail.';
    endif;
     
  7. Sponsor

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 733,556 other people just like you!

Loading...
Thread Status:
Not open for further replies.

Short URL to this thread: https://techguy.org/1211495

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice