Bootstrap Contact Form with PHP

Hello everyone,
I'm trying to create my first website.  I've been working on it for a while and my last hurdle is to get the contact form working correctly.  I downloaded an example from here but I can't get it to work.  

I'm running it through a local server using XAMPP.  I was able to get this really simple example to work so I think I have that part correct.

To run the form I enter this into the Nav bar of Firefox.
2015-06-19--11-39-07.jpg
But when I do this here is what I get.
2015-06-19--11-41-25.jpg
Like I said, this is my first website.  I know nothing about PHP or local servers, or anything else for that matter.  I've done a ton of googling but I can't seem to get this working.  Please help!!!

My ContactForm.php file is attached.

Thanks,
Kyle
ContactForm.php
LVL 12
kgerbChief EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
This is a technically incompetent PHP script.  The Bootstrap part may be good, but the PHP is not.  The Notice messages are only raised by PHP when error_reporting() is set to E_ALL, and that is not the default in most PHP installations.  Most PHP installations suppress the Notice messages, and many novice programmers believe that this means you can use undefined variables as if they were FALSE, empty(), zero, etc.  No professional PHP programmer would do that.

The problem comes up with statements like this value attribute from one of the form tags:

value="<?php echo htmlspecialchars($_POST['name']); ?>"

When PHP sees that code, it first looks in the $_POST array to find the 'name' element.  If there is no 'name' element defined in the $_POST array, PHP raises the Notice message you see, then it provides a context-appropriate default value since it needs something to send to the htmlspecialchars() function.  In this case, it sends an empty string of zero length.

The easy fix is probably (untested) to suppress the Notice messages, but that would get you fired from a programming job, since it's the software equivalent of putting a piece of black electrical tape over the warning lights on your dashboard.  You might try adding this statement to the top of the script:

error_reporting(E_ALL ^ E_NOTICE);

The correct fix is to test to see if the POST input is defined, and if not, provide reasonable default values for the value= attributes in the HTML tags.

If you're new to PHP and want some good learning resources, this article can help.  More importantly it will steer you away from the many simply terrible PHP code samples that litter the internet.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

This is my teaching example showing how to handle the external inputs. There are many ways to do this, but this one works and illustrates two important central principles, namely (1) Filter input and (2) Provide sensible default values.

<?php // demo/form_to_email.php
error_reporting(E_ALL);

// SEND MAIL FROM A FORM

// REQUIRED VALUES ARE PREPOPULATED - CHANGE THESE FOR YOUR WORK
$from = 'NoReply@Your.org';
$subj = 'Contact Form';

// THIS IS AN ARRAY OF RECIPIENTS - CHANGE THESE FOR YOUR WORK
$to[] = 'You@Your.org';
$to[] = 'Her@Your.org';
$to[] = 'Him@Your.org';


// IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
if (!empty($_POST['e']))
{
    // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
    $safe_mail = clean_string($_POST['e']);
    $safe_name = clean_string($_POST['n']);
    $safe_fone = clean_string($_POST['t']);
    $safe_idea = clean_string($_POST['i']);

    // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
    $content = NULL;
    $content .= "You have a New Query From $safe_name" . PHP_EOL . PHP_EOL;
    $content .= "Tel No: $safe_fone" . PHP_EOL;
    $content .= "Email: $safe_mail" . PHP_EOL;
    $content .= "Idea: $safe_idea" . PHP_EOL;

    // SEND MAIL TO EACH RECIPIENT
    foreach ($to as $recipient)
    {
        if (!mail( $recipient, $subj, $content, "From: $from\r\n"))
        {
            echo PHP_EOL . "<br/>MAIL FAILED FOR $recipient";
        }
        else
        {
            echo PHP_EOL . "<br/>MAIL WORKED FOR $recipient";
        }
    }

    // PRODUCE THE THANK-YOU PAGE
    echo '<p>THANK YOU</p>' . PHP_EOL;
    die('TASK COMPLETE');
}


// A FORM TO TAKE CLIENT INPUT FOR THIS SCRIPT
$form = <<<ENDFORM
<form method="post">
Please enter your contact information
<br/>Email: <input name="e" />
<br/>Phone: <input name="t" />
<br/>Name:  <input name="n" />
<br/>Ideas? <textarea name="i"></textarea>
<br/><input type="submit" />
</form>
ENDFORM;

echo $form;


// A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str)
{
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    // REMOVE EXCESSIVE INPUT
    $str = substr($str, 0, 255);

    return trim($str);
}

Open in new window

HTH, ~Ray
0
kgerbChief EngineerAuthor Commented:
Hello Ray,
Thanks for the response.  Instead of the electrical tape soluction I'll try to get a little foundation in PHP.  There is a CodeAcademy course on it which is what I'll do now.  When I finish hopefully I'll understand your answer better.  Please give me a second and I'll come back with more questions.  Thanks again for your response.

Kyle
0
Ray PaseurCommented:
10-4, Kyle, we will be glad to help.  CodeAcademy is pretty good, and so are the learning resource identified in the article!
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Ray PaseurCommented:
FWIW, This script worked correctly for me.  It uses the electrical tape "solution," but at least it gets useful results.  I marked the changes with comments.
<?php // demo/temp_kgerb.php
error_reporting(E_ALL ^ E_NOTICE);  // ********************* ERROR REPORTING LOWERED
    if (isset($_POST["submit"])) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $human = intval($_POST['human']);
        $from = 'Demo Contact Form';
        $to = 'Ray.Paseur@Gmail.com';  // ***************** EMAIL ADDRESS CHANGED
        $subject = 'Message from Contact Demo ';

        $body ="From: $name\n E-Mail: $email\n Message:\n $message";

        // Check if name has been entered
        if (!$_POST['name']) {
            $errName = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $errEmail = 'Please enter a valid email address';
        }

        //Check if message has been entered
        if (!$_POST['message']) {
            $errMessage = 'Please enter your message';
        }
        //Check if simple anti-bot test is correct
        if ($human !== 5) {
            $errHuman = 'Your anti-spam is incorrect';
        }

// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
    if (mail ($to, $subject, $body, $from)) {
        $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
    } else {
        $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
    }
}
    }
?>

<!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">
    <meta name="description" content="Bootstrap contact form with PHP example by BootstrapBay.com.">
    <meta name="author" content="BootstrapBay.com">
    <title>Bootstrap Contact Form With PHP Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  </head>
  <body>
      <div class="container">
          <div class="row">
              <div class="col-md-6 col-md-offset-3">
                  <h1 class="page-header text-center">Contact Form Example</h1>
                <form class="form-horizontal" role="form" method="post" action=""><!-- ***************** REMOVED ACTION ATTRIBUTE -->
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
                            <?php echo "<p class='text-danger'>$errName</p>";?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-10">
                            <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
                            <?php echo "<p class='text-danger'>$errEmail</p>";?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="message" class="col-sm-2 control-label">Message</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
                            <?php echo "<p class='text-danger'>$errMessage</p>";?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
                            <?php echo "<p class='text-danger'>$errHuman</p>";?>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10 col-sm-offset-2">
                            <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10 col-sm-offset-2">
                            <?php echo $result; ?>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
  </body>
</html>

Open in new window

0
kgerbChief EngineerAuthor Commented:
Okay, finished the CodeAcademy course.  It was good.  Now I know the syntax for associative arrays and other good stuff.  However, It didn't deal with external inputs like _Post and _Get so I still don't understand those.  Let me pour over your article for a while.  Then I'll go over your teaching example.  THEN, maybe I'll have intelligent question to ask.

Thanks for your patience.
Kyle

BTW, what is it with all these web dev languages and the { } [ ] brackets!!!  My little finger has a cramp.  I'll stick with VBA where all you need is a ".".  :-)
0
Ray PaseurCommented:
Yeah, every PHP variable starts with the shift key.
0
kgerbChief EngineerAuthor Commented:
Here goes.  I may be headed down a terrible path but this is what I have so far.  I removed all the PHP in the HTML body.  I added warning messages to the HTML and set their display attribute to 'none'.  I know inline styles are a bad thing but it's the only way I could get the style to take priority over the bootstrap CSS.  My idea is have the PHP check all the fields in the form after the Submit button is clicked and then hide/unhide the warning elements accordingly using the display property.  I looked online but all the examples I could find about how to hide/show a div from PHP had the PHP mixed up with the HTML.  Maybe because that's the correct way to do it and I'm off in left field (not sure).  Anway, obviously what I have now is not working but it's as far as I was able to get.  Thanks for any ideas you have.

Also, I'm getting two warning messages telling me several of my variables are not good.  I'm not sure what's wrong with them.
Error messages
<?php // demo/form_to_email.php
    error_reporting(E_ALL);

    // SEND MAIL FROM A FORM

    // REQUIRED VALUES ARE PREPOPULATED
    $from = 'NoReply@Your.org';
    $subj = 'Contact Form';

    // THIS IS THE RECIPIENT
    $recipient = 'kyletgerber@gmail.com';

    // This will tell us if the forms are filled out correctly and we can proceed with sending the email
    $GoodToGo = true;

    // Test the form fields
    if (!empty($_POST['name'])) {
        $GoodToGo = false;
            //Show #warnName
        }      
    
    if (!empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $GoodToGo = false;
            //Show #warnEmail
        }    
    
    if (!empty($_POST['message'])) {
        $GoodToGo = false;
            //Show #warnMessage
        }    
    
    if ($_POST['human'] !== 5) {
        $GoodToGo = false;
            //Show #warnHuman
        }    

    // IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
    if ($GoodToGo) {

        // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
        $safe_name = clean_string($_POST['name']);
        $safe_mail = clean_string($_POST['email']);
        $safe_message = clean_string($_POST['message']);

        // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
        $content = NULL;
        $content .= "You have a new message from " . $safe_name . PHP_EOL . PHP_EOL;
        $content .= "Email address: " . $safe_mail . PHP_EOL . PHP_EOL;
        $content .= "Message: ". $safe_message . PHP_EOL;

        // SEND MAIL TO RECIPIENT
        if (!mail($recipient, $subj, $content, "From: $from\r\n")) {
            //Show #Failure
        }
        else {
            //Show #Success
        }
    }

    //A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
    function clean_string($str){
        // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
        $str = stripslashes($str);

        // REMOVE EXCESS WHITESPACE
        $rgx
        = '#'                // REGEX DELIMITER
        . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
        . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
        . '#'                // REGEX DELIMITER
        ;
        $str = preg_replace($rgx, ' ', $str);

        // REMOVE UNWANTED CHARACTERS
        $rgx
        = '#'                // REGEX DELIMITER
        . '['                // START OF A CHARACTER CLASS
        . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
        . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
        . '"'                // KEEP DOUBLE QUOTES
        . "'"                // KEEP SINGLE QUOTES
        . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
        . ' '                // KEEP BLANKS
        . ']'                // END OF THE CHARACTER CLASS
        . '#'                // REGEX DELIMITER
        . 'i'                // CASE-INSENSITIVE
        ;
        $str = preg_replace($rgx, NULL, $str);

        // REMOVE EXCESSIVE INPUT
        $str = substr($str, 0, 255);

        return trim($str);
    }

?>

<!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">
        <meta name="description" content="Bootstrap contact form with PHP example by BootstrapBay.com.">
        <meta name="author" content="BootstrapBay.com">
        <title>Bootstrap Contact Form With PHP Example</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    </head>

    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    <h1 class="page-header text-center">Contact Form Example</h1>
                    <form class="form-horizontal" role="form" method="post" action=""><!-- ***************** REMOVED ACTION ATTRIBUTE -->
                        <div class="form-group">
                            <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name">
                            <p id="warnName" class='text-danger' style="display: none">The name field cannot be empty</p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-10">
                            <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com">
                            <p id="warnEmail" class='text-danger' style="display: none">This is not a valid email address</p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="message" class="col-sm-2 control-label">Message</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" rows="4" name="message"></textarea>
                            <p id="warnMessage" class='text-danger' style="display: none">What would you like to say?</p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
                            <p id="warnHuman" class='text-danger' style="display: none">The answer is not correct</p>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10 col-sm-offset-2">
                            <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10 col-sm-offset-2">
                            <div id:="Success" class="alert alert-success" style="display: none">Thank You! I will be in touch</div>
                            <div id:="Failure" class="alert alert-danger" style="display: none">Sorry there was an error sending your message. Please try again later.</div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
  </body>
</html>

Open in new window

0
Ray PaseurCommented:
A few changes that may help move on to the next step.  It looks like the logic is backwards in places.  For example, if $_POST['name'] is filled in, the script will set $GoodToGo to FALSE.  I don't think that's how you want it.
<?php // demo/temp_kgerb.php
error_reporting(E_ALL);

// SEND MAIL FROM A FORM

// REQUIRED VALUES ARE PREPOPULATED
$from = 'NoReply@Your.org';
$subj = 'Contact Form';

// THIS IS THE RECIPIENT
$recipient = 'kyletgerber@gmail.com';
// $recipient = 'ray.paseur@gmail.com'; // *********** TESTING

// This will tell us if the forms are filled out correctly and we can proceed with sending the email
$GoodToGo = true;

// ******************* IF THE FORM HAS BEEN SUBMITTED, SHOW ITS CONTENTS, THEN RUN THE ACTION SCRIPT
if (!empty($_POST))
{
    var_dump($_POST);

    // Test the form fields
    if (!empty($_POST['name'])) { // ******************** PROBABLY BACKWARDS LOGIC
        $GoodToGo = false;
            //Show #warnName
        }

    if (!empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $GoodToGo = false;
            //Show #warnEmail
        }

    if (!empty($_POST['message'])) {
        $GoodToGo = false;
            //Show #warnMessage
        }

    if ($_POST['human'] != 5) {  // **************** TEST FOR EQUAL, NOT IDENTICAL
        $GoodToGo = false;
            //Show #warnHuman
        }

    // IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
    if ($GoodToGo) {
        echo PHP_EOL . 'MAIL WILL BE SENT'; // ************** SEND A SIGNAL TO THE BROWSER

        // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
        $safe_name = clean_string($_POST['name']);
        $safe_mail = clean_string($_POST['email']);
        $safe_message = clean_string($_POST['message']);

        // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
        $content = NULL;
        $content .= "You have a new message from " . $safe_name . PHP_EOL . PHP_EOL;
        $content .= "Email address: " . $safe_mail . PHP_EOL . PHP_EOL;
        $content .= "Message: ". $safe_message . PHP_EOL;

        // SEND MAIL TO RECIPIENT
        if (!mail($recipient, $subj, $content, "From: $from\r\n")) {
            //Show #Failure
        }
        else {
            //Show #Success
        }
    }
}

//A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str){
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    // REMOVE EXCESSIVE INPUT
    $str = substr($str, 0, 255);

    return trim($str);
}

?>

<!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">
    <meta name="description" content="Bootstrap contact form with PHP example by BootstrapBay.com.">
    <meta name="author" content="BootstrapBay.com">
    <title>Bootstrap Contact Form With PHP Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <h1 class="page-header text-center">Contact Form Example</h1>
                <form class="form-horizontal" role="form" method="post" action=""><!-- ***************** REMOVED ACTION ATTRIBUTE -->
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name">
                        <p id="warnName" class='text-danger' style="display: none">The name field cannot be empty</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">Email</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com">
                        <p id="warnEmail" class='text-danger' style="display: none">This is not a valid email address</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="message" class="col-sm-2 control-label">Message</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" rows="4" name="message"></textarea>
                        <p id="warnMessage" class='text-danger' style="display: none">What would you like to say?</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
                        <p id="warnHuman" class='text-danger' style="display: none">The answer is not correct</p>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <div id:="Success" class="alert alert-success" style="display: none">Thank You! I will be in touch</div>
                        <div id:="Failure" class="alert alert-danger" style="display: none">Sorry there was an error sending your message. Please try again later.</div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>

Open in new window

0
kgerbChief EngineerAuthor Commented:
Ray,
Thanks.  You're right.  The logic was backwards.  I corrected it and now the $GoodToGo check seems to be working properly.  I added an echo to tell me if the mail function was completing and it says that it is successfully sending the mail.  

I have two problems left:
Even though the mail function says the message was sent successfully, I'm not receiving any of the test messages
How do I show/hide the warning elements

<?php // demo/temp_kgerb.php
error_reporting(E_ALL);

// SEND MAIL FROM A FORM

// REQUIRED VALUES ARE PREPOPULATED
$from = 'NoReply@Your.org';
$subj = 'Contact Form';

// THIS IS THE RECIPIENT
$recipient = 'kyletgerber@gmail.com';
// $recipient = 'ray.paseur@gmail.com'; // *********** TESTING

// This will tell us if the forms are filled out correctly and we can proceed with sending the email
$GoodToGo = true;

// ******************* IF THE FORM HAS BEEN SUBMITTED, SHOW ITS CONTENTS, THEN RUN THE ACTION SCRIPT
if (!empty($_POST)) {

    var_dump($_POST);

    // Test the form fields
    if (empty($_POST['name'])) {
        $GoodToGo = false;
            //Show #warnName
        }

    if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $GoodToGo = false;
            //Show #warnEmail
        }

    if (empty($_POST['message'])) {
        $GoodToGo = false;
            //Show #warnMessage
        }

    if ($_POST['human'] != 5) {
        $GoodToGo = false;
            //Show #warnHuman
        }

        var_dump($GoodToGo);

    // IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
    if ($GoodToGo) {
        echo PHP_EOL . 'Passed GoodToGo Check'; // ************** SEND A SIGNAL TO THE BROWSER

        // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
        $safe_name = clean_string($_POST['name']);
        $safe_mail = clean_string($_POST['email']);
        $safe_message = clean_string($_POST['message']);

        // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
        $content = NULL;
        $content .= "You have a new message from " . $safe_name . PHP_EOL . PHP_EOL;
        $content .= "Email address: " . $safe_mail . PHP_EOL . PHP_EOL;
        $content .= "Message: ". $safe_message . PHP_EOL;

        // SEND MAIL TO RECIPIENT
        if (!mail($recipient, $subj, $content, "From: $from\r\n")) {
            echo PHP_EOL . "Mail was not successful";
            //Show #Failure
        }
        else {
            echo PHP_EOL . "Mail was sent successfully";
            //Show #Success
        }
    }
}

//A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str){
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    // REMOVE EXCESSIVE INPUT
    $str = substr($str, 0, 255);

    return trim($str);
}

?>

<!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">
    <meta name="description" content="Bootstrap contact form with PHP example by BootstrapBay.com.">
    <meta name="author" content="BootstrapBay.com">
    <title>Bootstrap Contact Form With PHP Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <h1 class="page-header text-center">Contact Form Example</h1>
                <form class="form-horizontal" role="form" method="post" action=""><!-- ***************** REMOVED ACTION ATTRIBUTE -->
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name">
                        <p id="warnName" class='text-danger' style="display: none">The name field cannot be empty</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">Email</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com">
                        <p id="warnEmail" class='text-danger' style="display: none">This is not a valid email address</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="message" class="col-sm-2 control-label">Message</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" rows="4" name="message" placeholder="Enter your message here"></textarea>
                        <p id="warnMessage" class='text-danger' style="display: none">What would you like to say?</p>
                    </div>
                </div>
                <div class="form-group">
                    <label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
                        <p id="warnHuman" class='text-danger' style="display: none">The answer is not correct</p>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <div id:="Success" class="alert alert-success" style="display: none">Thank You! I will be in touch</div>
                        <div id:="Failure" class="alert alert-danger" style="display: none">Sorry there was an error sending your message. Please try again later.</div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>

Open in new window

0
Ray PaseurCommented:
function says the message was sent successfully, I'm not receiving any of the test messages
I'm little surprised.  The message has a from address that screams, "I'm Spam!"  When I changed from to your email address, the message got to me through Gmail.  But that's just the tip of the proverbial iceberg  of issues that you get into when you start trying to use automated email to communicate with your clients.  It's simply too big a subject to get into here, but I can tell you that I used to do exactly what you're trying, and in 2008 I simply gave up.  It was not worth the effort.  I wasted hundreds of hours debugging all kinds of clogs and stoppages in the email systems of several different ISPs.  It's hateful and thankless work, because everyone believes that email should "just work" and they cannot comprehend the complexity and lack of accountability that plague our efforts to use automated email.

Today most professional web developers would choose a professional email company like Constant Contact.  There are competitors, but I know Constant Contact from experience, and they do as good a job as can be done.  In any opt-in email list you're getting success rates in the top quintile if you get 35% of the messages opened.  Constant Contact can tell you all about it and they even offer a free trial.

Here is how I show and hide messages in a form.  You may be able to find some inspiration in the design.

<?php // demo/form_highlight_errors.php

/**
 * Demonstrate how to highlight errors in form input, and remember valid inputs
 * Client is asked to put in a value
 * If the value fails our test we show an error message
 * We put a marker next to the input control on the form
 * We turn the form border red
 * SEE http://www.w3schools.com/CSS/pr_class_visibility.asp
 */
error_reporting(E_ALL);


// THESE STYLE ELEMENTS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = $error_xyz = $error_any = 'hidden';
$boxer_abc = $boxer_xyz              = 'black';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;


// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        // VALIDATION FAILED
        $error_abc = $error_any = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        // VALIDATION FAILED
        $error_xyz = $error_any = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OTHERWISE... OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
kgerbChief EngineerAuthor Commented:
This post is dragging on so I only have one more question.  I took your example for hiding/showing divs with PHP and this is what I came up with.  It seems to work except for a couple of things...
The hide/show seems to work for all the warning messages except for Email.  Why is that
Now the Message textarea is hidden.  Why would the PHP affect another element like that?
Here's what I get when I load the page.
Contact form pictureHere's my code.
<?php // demo/temp_kgerb.php
error_reporting(E_ALL);

// SEND MAIL FROM A FORM

// REQUIRED VALUES ARE PREPOPULATED
$from = 'kyletgerber@gmail.com';
$subj = 'Contact Form';

//Initialize variables for display of warning messages
$dispName = 'none';
$dispEmail = 'none';
$dispMessage = 'none';
$dispHuman = 'none';
$dispFailure = 'none';
$dispSuccess = 'none';

// THIS IS THE RECIPIENT
$recipient = 'kyletgerber@gmail.com';
// $recipient = 'ray.paseur@gmail.com'; // *********** TESTING

// This will tell us if the forms are filled out correctly and we can proceed with sending the email
$GoodToGo = true;

// ******************* IF THE FORM HAS BEEN SUBMITTED, SHOW ITS CONTENTS, THEN RUN THE ACTION SCRIPT
if (!empty($_POST)) {

    // Test the form fields
    if (empty($_POST['name'])) {
        $GoodToGo = false;
        $dispName = 'block';
        }

    if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $GoodToGo = false;
        $dispEmail = 'block';
        }

    if (empty($_POST['message'])) {
        $GoodToGo = false;
        $dispMessage = 'block';
        }

    if ($_POST['human'] != 5) {
        $GoodToGo = false;
        $dispHuman = 'block';
        }

        echo $dispMessage;

    // IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
    if ($GoodToGo) {
        // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
        $safe_name = clean_string($_POST['name']);
        $safe_mail = clean_string($_POST['email']);
        $safe_message = clean_string($_POST['message']);

        // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
        $content = NULL;
        $content .= "You have a new message from " . $safe_name . PHP_EOL . PHP_EOL;
        $content .= "Email address: " . $safe_mail . PHP_EOL . PHP_EOL;
        $content .= "Message: ". $safe_message . PHP_EOL;

        //Construct the header
        // $mailheader .= "Reply-To: Some One <someone@mydomain.com>\r\n"; 
        // $mailheader .= "Return-Path: Some One <someone@mydomain.com>\r\n"; 
        // $mailheader .= "From: Some One <mydomain@myhost.com>\r\n"; 
        // $mailheader .= "Organization: My Organization\r\n"; 
        // $mailheader .= "Content-Type: text/plain\r\n"; 

        // SEND MAIL TO RECIPIENT
        if (!mail($recipient, $subj, $content, "From: $from\r\n")) {
            echo PHP_EOL . "Mail was not successful";
            $dispFailure = 'block';
        }
        else {
            echo PHP_EOL . "Mail was sent successfully";
            echo PHP_EOL . $dispMessage;
            $dispSuccess = 'block';
        }
    }
}

//A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str){
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    // REMOVE EXCESSIVE INPUT
    $str = substr($str, 0, 255);

    return trim($str);
}

?>

<!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">
    <meta name="description" content="Bootstrap contact form with PHP example by BootstrapBay.com.">
    <meta name="author" content="BootstrapBay.com">
    <title>Gerber Engineering</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <h1 class="page-header text-center">Contact Form Example</h1>
                <form class="form-horizontal" role="form" method="post" action=""><!-- ***************** REMOVED ACTION ATTRIBUTE -->
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name">
                        <?php echo "<p class='text-danger' style='display: $dispName'>The name field cannot be empty</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">Email</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com">
                        <?php echo "<p class='text-danger' style='display: $dispEmail>This is not a valid email address</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <label for="message" class="col-sm-2 control-label">Message</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" rows="4" name="message" placeholder="Enter your message here"></textarea>
                        <?php echo "<p class='text-danger' style='display: $dispMessage'>What would you like to say?</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
                        <?php echo "<p class='text-danger' style='display: $dispHuman'>The answer is not correct</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <?php echo "<div class='alert alert-success' style='display: $dispSuccess'>Thank You! I will be in touch</div>";?>
                        <?php echo "<div class='alert alert-danger' style='display: $dispFailure'>Sorry there was an error sending your message. Please try again later.</div>";?>
                    </div>
                </div>
            </form>
        </div>
    </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>

Open in new window

0
kgerbChief EngineerAuthor Commented:
Never mind!  Ahhhh!  I forgot the end quote in the email element PHP statement.
I'm an idiotNow it's working correctly.
Here's the final version.  I'm still not receiving any emails but that's another question.
<?php // demo/temp_kgerb.php
error_reporting(E_ALL);

// SEND MAIL FROM A FORM

// REQUIRED VALUES ARE PREPOPULATED
$from = 'kyletgerber@gmail.com';
$subj = 'Contact Form';

//Initialize variables for display of warning messages
$dispName = 'none';
$dispEmail = 'none';
$dispMessage = 'none';
$dispHuman = 'none';
$dispFailure = 'none';
$dispSuccess = 'none';

// THIS IS THE RECIPIENT
$recipient = 'kyletgerber@gmail.com';
// $recipient = 'ray.paseur@gmail.com'; // *********** TESTING

// This will tell us if the forms are filled out correctly and we can proceed with sending the email
$GoodToGo = true;

// ******************* IF THE FORM HAS BEEN SUBMITTED, SHOW ITS CONTENTS, THEN RUN THE ACTION SCRIPT
if (!empty($_POST)) {

    // Test the form fields
    if (empty($_POST['name'])) {
        $GoodToGo = false;
        $dispName = 'block';
        }

    if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $GoodToGo = false;
        $dispEmail = 'block';
        }

    if (empty($_POST['message'])) {
        $GoodToGo = false;
        $dispMessage = 'block';
        }

    if ($_POST['human'] != 5) {
        $GoodToGo = false;
        $dispHuman = 'block';
        }

        echo $dispMessage;

    // IF THE DATA HAS BEEN POSTED (AT LEAST SOMETHING IN THE EMAIL INPUT CONTROL)
    if ($GoodToGo) {
        // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
        $safe_name = clean_string($_POST['name']);
        $safe_mail = clean_string($_POST['email']);
        $safe_message = clean_string($_POST['message']);

        // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
        $content = NULL;
        $content .= "You have a new message from " . $safe_name . PHP_EOL . PHP_EOL;
        $content .= "Email address: " . $safe_mail . PHP_EOL . PHP_EOL;
        $content .= "Message: ". $safe_message . PHP_EOL;

        //Construct the header
        // $mailheader .= "Reply-To: Some One <someone@mydomain.com>\r\n"; 
        // $mailheader .= "Return-Path: Some One <someone@mydomain.com>\r\n"; 
        // $mailheader .= "From: Some One <mydomain@myhost.com>\r\n"; 
        // $mailheader .= "Organization: My Organization\r\n"; 
        // $mailheader .= "Content-Type: text/plain\r\n"; 

        // SEND MAIL TO RECIPIENT
        if (!mail($recipient, $subj, $content, "From: $from\r\n")) {
            echo PHP_EOL . "Mail was not successful";
            $dispFailure = 'block';
        }
        else {
            echo PHP_EOL . "Mail was sent successfully";
            echo PHP_EOL . $dispMessage;
            $dispSuccess = 'block';
        }
    }
}

//A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str){
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    // REMOVE EXCESSIVE INPUT
    $str = substr($str, 0, 255);

    return trim($str);
}

?>

<!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">
    <meta name="description" content="Bootstrap contact form with PHP example by BootstrapBay.com.">
    <meta name="author" content="BootstrapBay.com">
    <title>Gerber Engineering</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <h1 class="page-header text-center">Contact Form Example</h1>
                <form class="form-horizontal" role="form" method="post" action=""><!-- ***************** REMOVED ACTION ATTRIBUTE -->
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name">
                        <?php echo "<p class='text-danger' style='display: $dispName'>The name field cannot be empty</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">Email</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="email" name="email" placeholder="example@domain.com">
                        <?php echo "<p class='text-danger' style='display: $dispEmail'>This is not a valid email address</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <label for="message" class="col-sm-2 control-label">Message</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" rows="4" name="message" placeholder="Enter your message here"></textarea>
                        <?php echo "<p class='text-danger' style='display: $dispMessage'>What would you like to say?</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
                        <?php echo "<p class='text-danger' style='display: $dispHuman'>The answer is not correct</p>";?>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <?php echo "<div class='alert alert-success' style='display: $dispSuccess'>Thank You! I will be in touch</div>";?>
                        <?php echo "<div class='alert alert-danger' style='display: $dispFailure'>Sorry there was an error sending your message. Please try again later.</div>";?>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>

Open in new window

0
kgerbChief EngineerAuthor Commented:
Thank you sooooo much!  Thanks for your patience.  Thanks for encouraging me to get a foundation in the language and not just spoon feeding me (which is what I originally wanted).  Thanks for not flaming me even though I a brand newbie.  I really appreciate your help.

Kyle
0
Ray PaseurCommented:
Glad things are pointed in the right direction!  All the best, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.