Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDennis Planner
2,914 PointsBuild a Simple PHP validation Application - Validating the contact form using red text underneath each fields.
Hello all.
I'm using this track as a guide to make a contact form, but additionally displays red alert display messages below the form fields if they're incorrect or missing.
However it doesn't seem to work when I press the submit button: It submits it successfully regardless.
I borrowed the logic from the following website: http://bootstrapbay.com/blog/working-bootstrap-contact-form/
My PHP code is:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
// VARIABLE DECLARATIONS
$errName = '<p></p>';
$errEmail = '<p></p>';
$errMessage = '<p></p>';
// CLASS DECLARATIONS
require_once("includes/PHPMailer/class.phpmailer.php");
$mail = new PHPMailer();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]); //trim destroys whitespaces like "Tab" or "Spacebar"
$email = trim($_POST["email"]);
$message = trim($_POST["message"]);
//$attachment = trim($_POST["attachment"]);
// Attack #1 preventor - Spam Honeypot
if ($_POST["address"] != "") {
echo "SPAM HONEYPOT";
exit;
}
// Attack #2 preventor - Email header injection hack preventor
foreach($_POST as $value) {
if(stripos($value, 'Content-Type:') !== FALSE) {
echo "There was a problem with the information you entered.";
exit;
}
}
// Check if name has been entered
if ($name == "") {
$errName = 'Please enter your name';
exit;
}
// Check if message has been entered
if ($message == "") {
$errMessage = 'Please enter your message';
}
// Check if email is valid
if (!$mail->validateAddress($email)) {
$errEmail = 'Please enter a valid email address';
}
// EMAIL BODY IFF FORM VALIDATION IS SUCESSFULL!
$email_body = "";
$email_body = $email_body. "Name: " . $name . "<br>";
$email_body = $email_body. "Email: " . $email . "<br>";
$email_body = $email_body. "Message: " . $message;
date_default_timezone_set('Etc/UTC');
require ('/includes/PHPMailer/PHPMailerAutoload.php');
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = ######;
//Password to use for SMTP authentication
$mail->Password = ######;
//Set who the message is to be sent from
$mail->setFrom($email, $name);
//Set who the message is to be sent to
$mail->addAddress('perpetualprinting@gmail.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Add attachment
//if (isset($_FILES['uploaded_file']) &&
// $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
// $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
// $_FILES['uploaded_file']['name']);
//
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($email_body);
//send the message, check for errors
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
} else {
}
header("Location: contact.php?status=thanks");
exit;
}
?>
HTML
<html>
<head>
<?php include('includes/bootstrap.php'); ?>
<title>Imperial 3D | Contact Us</title>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[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>
<div class = 'container'>
<!--navbar-->
<nav class="navbar navbar-default navbar-inverse">
<?php include('includes/navbar.php'); ?>
</nav>
<!--body-->
<div class = "wrapper">
<section class ="bulk"
<div class ="row">
<h1 class = "text-center">
Contact
</h1>
<p class = "text-center">
We'd love to hear from you! Complete the form to contact me.
</p>
</div>
<?php if(isset($_GET["status"]) == "thanks") { ?>
<p> Thanks for the email! I'll be in touch shortly </p>
<?php } else { ?>
<!-- form stuff -->
<div class ="row">
<div class ='col-md-6'>
<form method ="post" action ="contact.php" enctype='multipart/form-data'>
<div class="form-group">
<label for="name">Name</label>
<input type ="text" class="form-control" name="name" id ="name" placeholder="Enter name">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<!--email-->
<div class="form-group">
<label for="email">Email</label>
<input type ="text" class="form-control" name="email" id ="email" placeholder="Enter email">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
<!--msg-->
<div class="form-group">
<label for="message">Message</label>
<textarea name ="message" class="form-control" id ="message" placeholder="Enter message"></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
<!--attachments-->
<div class="form-group" style="visibility:hidden">
<label for="attachment" >Attachment</label>
<input type ="file" name='uploaded_file' id='uploaded_file'>
</div>
<!--Hpam Sponypot -->
<div class="form-group" style="visibility: hidden">
<label for="address">Address</label>
<input type ="text" name="address" id ="address">
<p> Humans, do not fill out this form! </p>
</div>
<!--attachments-->
<button type="submit" value="Send" class="btn btn-default">Submit</button>
<?php echo $result; ?>
</form>
</div>
<!-- contact details -->
<div class ='col-md-6'>
<h3> Contact Details </h3>
<ul class = "contact-info">
<li>Dennis.</li>
<li class ="phone"><span class="glyphicon glyphicon-earphone"></span><span><?php echo" Tel: " ?></span><a href ="tel:04040404">04040404</a></li>
</ul>
</div>
</div>
<?php } ?>
</section>
<div class ="pusher">
<?php include('includes/footer.php'); ?>
</div>
</div>
</div>
</body>
</html>
```
4 Answers
thomascawthorn
22,986 PointsYou're never checking that your entire form is invalid. You are checking certain fields if they're empty etc.. but you're not saying 'If an error message exists, don't continue creating the email body and sending the mail'.
I would do something like this:
<?php
$errorMessages = [];
$requiredFields = ['name', 'email'];
foreach($requiredFields as $requiredField) {
if ( ! array_key_exists($requiredField, $_POST) || empty($_POST[$requiredField])) {
$errorMessages[$requiredField] = 'You cannot leave'. $requiredField .'blank';
}
}
// This is the check you're missing:
if ($errorMessages) { // empty array == false
// form is invalid because error messages have been set
}
// form is valid
Dennis Planner
2,914 PointsAh I see. The for loop creates an error message for all cases (name, email, message) through concatenation by doing the logic check "If the particular required field is NOT in the post array, as in empty/null ".
Then a second conditional check to see if the $errorMessage contains a concatenated string that evaluates to True, False will continue the rest of the code as normal.
What I don't know is how to flag the form as invalid e.g. would it be a class method or a function to do so.
Currently I can only think of
if ($errorMessages) {
//php html variable = $errormessage
exit();
}
That however just leads the webpage to a blank white screen when I press submit with one form value empty.
Dennis Planner
2,914 PointsActually I think I know,
I should've moved everything in an else branch below the validating if statement, I'll try it now.
Dennis Planner
2,914 PointsYES! it did work,
if ($errorMessages) {
//php html variable = $errormessage
exit();
} else {
// PUT the rest of the PHP
}
thomascawthorn
22,986 Pointsthomascawthorn
22,986 PointsIt also looks like you're pulling in PHPMailer twice - you should only need one of those requires, and requires are best placed right at the top of your script.