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.

PHP Contact Form Help

Discussion in 'Web Design & Development' started by howard.a.s, Nov 2, 2018.

Advertisement
  1. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    Hi there!

    This post relates to https://github.com/bryanmcdee/Bootstrap-Ajax-PHP-ContactForm

    Not being sure as to how to set this up on my own website, I've done the following

    Code:
    <?php
    $name = trim($_POST["name"]);
    $email = trim($_POST["email"]);
    $message = trim($_POST["message"]);
    $honeypotEmail = trim($_POST["honeypotEmail"]);
    $formIsValid = true;
    $errorMessage = "There was an error sending your email. Please try again.";
     
    if ($honeypotEmail != "") {
        $formIsValid = false;
        echo $errorMessage;
            exit;
    }
     
    $emailTo = "[email protected]";
    $subject = "New Message From Your Contact Form";
     
    // email body
    $email_body = "";
    $email_body .= "Name: " . $name . "\n";
    $email_body .= "Email: " . $email . "\n";
    $email_body .= "Message: " . $message  . "\n";;
    // verify the contact form fields are not blank
    if ($name == "" OR $email == "" OR $message == "") {
        $errorMessage = "You must specify a value for name, email address, and message.";
        $formIsValid = false;
    }
    // verify the message doesn't contain certain words
    $invalidWords = array('www', '.com', 'http');
    foreach($invalidWords as $word)
    {
        if (strpos($message,$word) !== false) {
            $errorMessage = "Your message can't contain a link or email address.";
            $formIsValid = false;
            break;
        }
    }
    // send email
    if ($formIsValid) {
        $success = mail($emailTo, $subject, $email_body, "From:".$email);
        if ($success){
            echo "success";
            exit;
        } else {
            echo $errorMessage;
            exit;
        } 
    } else {
        echo $errorMessage;
        exit;
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Contact</title>
    
        <!-- Bootstrap -->
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <!-- Custom -->
        <link href="css/site.css" rel="stylesheet">
        
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
      </head>
      <body>
          <br/>
          <br/>
          
          <div class="col-md-offset-3 col-md-6">
                <div class="panel panel-primary">
                    <div class="panel-heading">Contact Me</div>
                    <div id="contactFormBody" class="panel-body">
                        <form role="form" id="contactForm" role="form">
                            <div class="form-group col-sm-12">
                                <div class="form-group">
                                    <label for="name" class="control-label">Name</label>
                                    <input type="text" class="form-control" id="name" placeholder="Enter your name" data-error="Enter your name." required>
                                    <div class="help-block with-errors"></div>
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label for="email" class="control-label">Email</label>
                                <input type="email" class="form-control" id="email" placeholder="Enter your email address" data-error="Enter a valid email address." required>
                                <div class="help-block with-errors"></div>
                            </div>
                            <div id="honeypotEmailDiv" class="form-group col-sm-12">
                                <input id="honeypotEmail" class="form-control" type="text" name="email" value="" />
                            </div>
                            <div class="form-group col-sm-12">
                                <label for="message">Message</label>
                                <textarea id="message" class="form-control" rows="5" placeholder="Enter your message" data-error="Enter a message." required></textarea>
                                <div class="help-block with-errors"></div>
                            </div>                       
                            <div class=col-xs-12>
                                <div class="form-group">
                                    <button type="submit" class="btn btn-primary btn-lg col-sm-offset-4 col-sm-4 col-xs-12"">Submit</button>
                                </div>
                            </div>
                        </form>                   
                        <div id="formSuccessMessage" class="col-xs-12 text-center bg-success" style="display:none;">
                            <h4>Thank you. Your form has been submitted <span>successfully!</span></h4>
                            <h4>I will get back to you shortly.</h4>
                        </div>
                        <div id="formErrorMessage" class="col-xs-12 text-center bg-danger" style="display:none;">
                            <h4>Sorry. There was an error submitting your form.</h4>
                            <h4 id="phpErrorMessage"></h4>                       
                        </div>
                    </div>
                </div>
            </div>
        <!-- jQuery -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <!-- Bootstrap -->
        <script src="js/bootstrap.min.js"></script>
        <!-- Custom js -->
        <script src="js/script.js"></script>
        <!-- validation -->
        <script src="js/validator.js"></script>
      </body>
    </html>
    I've saved the necessary css and js to their own respective folders and also checked the links to css and js work properly.

    Of course, I'll need to change the $emailTo = "[email protected]"; so as to include my own email address.

    When I test my page offline, the form displays perfectly.

    When I upload this page and its associated folders to my hosting and check my page online, all I see is the message 'You must specify a value for name, email address, and message.'

    The form itself does not display. Just this message.

    Am I missing something?

    Should the php code be saved to the head of my html page or to a separate file?

    Any constructive suggestions gratefully received.
     
  2. JiminSA

    JiminSA

    Joined:
    Dec 15, 2011
    Messages:
    3,240
    First Name:
    Jim
    Hi Howard;)
    May I suggest that you take out the check for empty fields PHP code?
    PHP:
    // verify the contact form fields are not blank
    if ($name == "" OR $email == "" OR $message == "") {
        
    $errorMessage "You must specify a value for name, email address, and message.";
        
    $formIsValid false;
    }
    This is superfluous as your form will not submit without all fields filled in.
    Good as is ...

    But to answer the question ...
    This is happening on load because you are not checking to see if the form has been posted and you're executing the form validation PHP code regardless:( and $name $email and $message variables are empty:eek:
    Why the problem does not occur offline, is probably because you are not 'running' your page in the browser, using a (xaamp or wamp) pseudo server platform and PHP is therefore not executed. Enclose your PHP code so ...
    PHP:
    if(!empty($_POST))
    {
        .... 
    YOUR PHP CODE HERE ...
    }
     
    Last edited: Nov 3, 2018
  3. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    Hi Jim and thanks for your reply. Yes, you are right. When I test my page offline this is not done by running through a pseudo-server which must be the reason why the problem does not occur. I’m just beginning to embark upon learning php, but I think it’s likely to be quite some time before I am able to have a proper understanding of how this all works. In the meantime, I’m struggling to understand the part where you suggest that I should enclose my php in the example provided. Please would you be able to post my existing page source code with the necessary alterations having been included, otherwise I guess I’m not going to be able to understand what needs to be done. I’ve been considering swapping out my existing contact form which uses captcha images ever since you first mentioned to me in a previous post how you preferred a more subtle approach using honeypot. I came upon the code this post relates to and because it appeared relatively simple to set up decided to give it a try. By altering the code in the way you suggest, is this likely to stop the honeypot effect from working? And, just as important, how do I check that the honeypot effect is actually working? Another reason for my wanting to swap out my existing form with captcha is that although this works perfectly on Firefox, Chrome, Edge, IE, Safari, it fails to work properly in IOS. I am hoping that this new form will also work in IOS. Oh, before I end this message and to save me starting a new post, do you know whether it is a simple matter to lazy load images in bootstrap carousels and whether the effects on page speed by doing this would be worth the effort? As always, any advice and suggestions would be gratefully received. Thanks for your time Jim. I really do appreciate your help.
     
  4. JiminSA

    JiminSA

    Joined:
    Dec 15, 2011
    Messages:
    3,240
    First Name:
    Jim
    PHP:
    <?php

        
    if(!empty($_POST))
        {

            
    $name trim($_POST["name"]);
            
    $email trim($_POST["email"]);
            
    $message trim($_POST["message"]);
            
    $honeypotEmail trim($_POST["honeypotEmail"]);
            
    $formIsValid true;
            
    $errorMessage "There was an error sending your email. Please try again.";
            
            if (
    $honeypotEmail != "") {
                
    $formIsValid false;
                echo 
    $errorMessage;
                    exit;
            }
            
            
    $emailTo "[email protected]";
            
    $subject "New Message From Your Contact Form";
            
            
    // email body
            
    $email_body "";
            
    $email_body .= "Name: " $name "\n";
            
    $email_body .= "Email: " $email "\n";
            
    $email_body .= "Message: " $message  "\n";;
            
    // verify the contact form fields are not blank
            
    if ($name == "" OR $email == "" OR $message == "") {
                
    $errorMessage "You must specify a value for name, email address, and message.";
                
    $formIsValid false;
            }
            
    // verify the message doesn't contain certain words
            
    $invalidWords = array('www''.com''http');
            foreach(
    $invalidWords as $word)
            {
                if (
    strpos($message,$word) !== false) {
                    
    $errorMessage "Your message can't contain a link or email address.";
                    
    $formIsValid false;
                    break;
                }
            }
            
    // send email
            
    if ($formIsValid) {
                
    $success mail($emailTo$subject$email_body"From:".$email);
                if (
    $success){
                    echo 
    "success";
                    exit;
                } else {
                    echo 
    $errorMessage;
                    exit;
                }
            } else {
                echo 
    $errorMessage;
                exit;
            }
        }
    ?>
    No, not at all;)
    Insert this snippet for a once-off test and remove the first line straight after ...
    PHP:
    $honeypotEmail "Trapped!";       
            if (
    $honeypotEmail != "") {
                
    $formIsValid false;
                echo 
    $errorMessage;
                    exit;
            }
    If by "lazy load" you mean preload the images, it's effective for a large number of slides, but for 3 or 4, I wouldn't bother:)
     
  5. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    Thanks Jim. That all makes sense. And as to the honeypot test, is it right that I would add the line $honeypotEmail = “Trapped!”; directly above the existing if ($honeypotEmail !=“”) { and then remove this line so as to fall back to the original code straight after? One other quick question. I was experimenting making some alterations to my page in an attempt to reduce page load time and found that by converting existing jpgs to progressive jpgs made a substantial improvement. This having been said, when I also then swapped images included in carousels over to progressive jpgs this seemed to substantially increase page loading time, sending my page speed rating tumbling from 78 back down to 65. Would this be something you’d expect to happen and is it best to just leave images included as part of a carousel as standard jpgs?
     
  6. JiminSA

    JiminSA

    Joined:
    Dec 15, 2011
    Messages:
    3,240
    First Name:
    Jim
    That's dead right Howard(y) - forgive my not explaining it more succinctly:(
    I had never heard of progressive jpg's, until today. Having looked at their usage, I would recommend preloading them as you wouldn't want users seeing them until they're properly formed and yes I can see how they might increase page load time ... may I suggest that you consider using a loading screen while the preloader does it's thing? That is if your carousel is prime view on a landing page?
     
  7. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    https://coderwall.com/p/6qaeya/lazy-carousel-in-bootstrap Would something like this serve the purpose of carousel image preloader? If my understanding of how to include this is correct, I wrap my existing carousel code in the carousel lazy class, update the links to my images from img src to img data-src (all except for the first image) and then add the JavaScript to make it all work? Would this single script work for all 3 carousels I have running on my landing page simply by wrapping each in the same lazy class and updating the img src? If this image loader isn’t what I need, please can you suggest a suitable script?
     
  8. JiminSA

    JiminSA

    Joined:
    Dec 15, 2011
    Messages:
    3,240
    First Name:
    Jim
    My bad, I had not really understood how progressive jpgs work, but now do. They give an impression of being fully loaded, because there is no top to bottom rendering, so that an img is fully shown in an initial distorted state, which becomes progressively clearer.
    In this case preloading - waiting for all images to load before showing the page - is counter-productive ...
    Your scenario of having one carousel in the initial viewport and several more further down the page lends itself to using lazy load, because page load does not require img loads unless they are in the viewport. Meaning that the initial page load is not dependant on all imgs being loaded and therefore much faster.
    IMO, whether you use progressive or baseline jpegs should not influence lazy load or page load timings, as it is perceptual not actual.
    Does that make sense?;)
     
  9. JiminSA

    JiminSA

    Joined:
    Dec 15, 2011
    Messages:
    3,240
    First Name:
    Jim
    Yes indeed Howard. That would be the correct way to lazy load and the javascript would operate for each carousel generically:) You can safely disregard my reference to preloading as it's unnecessary ...
     
  10. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    Thanks Jim, I’ll give all of the things we’ve discussed a try today and let you know how I get on.
     
  11. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    Okay. Just reporting back on my progress this far.

    I've copied and pasted the altered contact form php into the head of my page and uploaded to a test folder http://www.themetaldetective.co.uk/optimization2/contact.php

    The form displays properly, so all's good so far.

    When I fill out the form and attempt to send I receive an error message saying that there is a problem and that the message cannot be sent.

     
  12. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    I had already replaced the example email address in the line
    Code:
    $emailTo = "[email protected]";
    with my actual email address.

    I remembered how I'd had problems with a couple of different forms sending via my web host about a year ago and how this had been corrected by making the following alterations
    Code:
    Before:
    
    $email = $_POST['email'];
    $message = $_POST['message'];
    
    After:
    
    $email = $_POST['[email protected]'];
    $message = $_POST['message']; 
    Code:
    Before:
    
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    $from = $_POST["from"];
    $verif_box = $_POST["verif_box"];
    
    After:
    
    $subject = $_POST["subject"];
    $message = $_POST["message"];
    $from = $_POST["[email protected]"];
    $verif_box = $_POST["verif_box"];
    After closely checking the php this post relates to, I tried making the following alteration

    Before:

    Code:
    $email = trim($_POST["email"]);
    After:

    Code:
    $email = trim($_POST["[email protected]"]);
    Replacing the word "email" with my actual email address (obviously not the examples shown here)

    so that the entire code then looks like this

    Code:
    <?php
    
        if(!empty($_POST))
        {
    
            $name = trim($_POST["name"]);
            $email = trim($_POST["[email protected]"]);
            $message = trim($_POST["message"]);
            $honeypotEmail = trim($_POST["honeypotEmail"]);
            $formIsValid = true;
            $errorMessage = "There was an error sending your email. Please try again.";
       
            if ($honeypotEmail != "") {
                $formIsValid = false;
                echo $errorMessage;
                    exit;
            }
       
            $emailTo = "[email protected]";
            $subject = "New Message From Your Contact Form";
       
            // email body
            $email_body = "";
            $email_body .= "Name: " . $name . "\n";
            $email_body .= "Email: " . $email . "\n";
            $email_body .= "Message: " . $message  . "\n";;
            // verify the contact form fields are not blank
            if ($name == "" OR $email == "" OR $message == "") {
                $errorMessage = "You must specify a value for name, email address, and message.";
                $formIsValid = false;
            }
            // verify the message doesn't contain certain words
            $invalidWords = array('www', '.com', 'http');
            foreach($invalidWords as $word)
            {
                if (strpos($message,$word) !== false) {
                    $errorMessage = "Your message can't contain a link or email address.";
                    $formIsValid = false;
                    break;
                }
            }
            // send email
            if ($formIsValid) {
                $success = mail($emailTo, $subject, $email_body, "From:".$email);
                if ($success){
                    echo "success";
                    exit;
                } else {
                    echo $errorMessage;
                    exit;
                }
            } else {
                echo $errorMessage;
                exit;
            }
        }
    ?>
    but still my form refuses to send.

    I'm pretty lost as to what else I can do now, especially given my present lack of understanding of PHP.

    Please are you able to offer any advice, other than to abandon the idea entirely! o_O
     
  13. JiminSA

    JiminSA

    Joined:
    Dec 15, 2011
    Messages:
    3,240
    First Name:
    Jim
    When you declare
    PHP:
    $email trim($_POST["[email protected]"]);
    you are saying that there is a form element called
    [email protected] which contains the email address to be used:(
    Rather hard code the address to be used like so ...
    Code:
    $email = "[email protected]";
    ;)
     
  14. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    By the way, just in case it helps, here is what my web host had to say about the reasons why my previous forms failed to send:

    "In order for the server to send out the e-mails, you need to ensure that in the contact forms you will set as "FROM" an e-mail address associated with the domain name used for the site; e.g. if the contact form is used on mydomain.com, the "FROM" e-mail address needs to be something in line with [email protected] (this email address doesn't necessarily have to exist)."

    Of course, I have no idea whether this has anything to do with the reasons why my current form is not sending, but just thought it worthy of a mention.

    I don't even know if I've made these changes in the right place on my new form, or whether it would even make a difference anyway?
     
  15. howard.a.s

    howard.a.s Thread Starter

    Joined:
    Jul 22, 2005
    Messages:
    490
    I think our posts may have overlapped as I've just read your previous. In your reply you mention the line
    Code:
    $email = "[email protected]";
    Should I add this as a new line in the existing PHP and whereabouts would I place it?
     
  16. 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...

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

  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