Even the errors fields fnameErr, lnameErr are empty my code is still printing "Do not send an email"
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "First Name is required";
} else {
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
}
$stop=true;
}
if (empty($_POST["lname"])) {
$lnameErr = "Last Name is required";
} else {
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
}
$stop=true;
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
$stop=true;
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is required";
$stop=true;
}
if (empty($_POST["comment"])) {
$commentErr = "Comments is required";
$stop=true;
}
if(!$stop)
{
echo "send an email";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
my HTML code
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<h4> </h4>
<div class="form-group">
<div class="col-md-6">
<input id="fname" name="fname" type="text" placeholder="First Name" class="form-control" value="<?php echo $_POST["fname"];?>"><span class="error"><?php echo $fnameErr;?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input id="lname" name="lname" type="text" placeholder="Last Name" class="form-control" value="<?php echo $_POST["lname"];?>"><span class="error"><?php echo $lnameErr;?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input id="email" name="email" type="text" placeholder="Email Address" class="form-control" value="<?php echo $_POST["email"];?>"><span class="error"><?php echo $emailErr;?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input id="phone" name="phone" type="text" placeholder="Phone" class="form-control" value="<?php echo $_POST["phone"];?>"><span class="error"><?php echo $phoneErr;?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" id="comment" name="comment" placeholder="Enter your message" rows="7"><?php echo $_POST["comment"];?></textarea><span class="error"><?php echo $commentErr;?></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12 text-left">
<button type="submit" name="submit" class="btn btn-primary readmmore">Submit</button>
</div>
</div>
</fieldset>
</form>
if you want only fNameErr and LnameErr to stop the send then you'll have to use:
if(empty($fnameErr) && empty(lnameErr) && empty(emailErr) && empty(phoneErr) && empty(commentErr))
{
echo "send an email";
}
Try this(you were setting $stop to true in the wrong places):
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
// Let's explicityly set $stop to false(some PHP settings require this)
$stop = False;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "First Name is required";
$stop=true;
} else {
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fnameErr = "Only letters and white space allowed";
$stop=true;
}
}
if (empty($_POST["lname"])) {
$lnameErr = "Last Name is required";
$stop=true;
} else {
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
$stop=true;
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$stop=true;
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$stop=true;
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is required";
$stop=true;
}
if (empty($_POST["comment"])) {
$commentErr = "Comments is required";
$stop=true;
}
if ($stop){
// Validation failed, dont send email
} else {
// Validation passed, send email
}
}
Related
I am trying to create a form that checks and validates name, email. But I can't see any error messages. I don't know a lot of PHP, can't say that I even know the basics.
Here is the code:
<iframe name="formDestination" class="nnn"></iframe>
<div class="container33">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="thwid" method="post" target="formDestination">
<label for="fname">Full Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your full name..." value="<?php echo $name;?>"><span class="error">* <?php echo $nameErr;?></span>
<label for="email">Your E-mail</label>
<input type="text" id="email" name="email" placeholder="Your E-mail adress..."> <span class="error">* <?php echo $emailErr;?></span>
<label for="message">Your message</label>
<textarea id="message" name="message" placeholder="Write your message here / the reason why you want to contact us " ></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<?php
if(isset($_POST['submit'])){
$to = "myemail#cencored.com";
$from = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
} ?>
<?php
$nameErr = $emailErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}?>
Move the form HTML code below all of the PHP code otherwise your error variables such as $emailErr won't be displayed as they are not defined before they are used.
Re-positioned code blocks in their proper places. Also deleted unneeded codes.
Try:
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['submit'])){
$emailErr = "";
$name = $email = $comment = "";
$nameErr = "";
if (empty($_POST["fullname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["fullname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if( trim( $emailErr ) == "" AND trim( $nameErr ) == "" ) {
$to = "2myemail#cencored.com";
$from = $_POST['email'];
$first_name = $_POST['fullname'];
$last_name = $_POST['last_name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $first_name . " " . $last_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
}
}?>
<style>.error { color:red; } </style>
<!-- <iframe name="formDestination" class="nnn"></iframe> -->
<div class="container33">
<form action="" class="thwid" method="post">
<label for="fname">Full Name</label>
<input type="text" id="fname" name="fullname" placeholder="Your full name..." value="<?php echo #$name;?>"><span class="error">* <?php echo #$nameErr;?></span>
<label for="email">Your E-mail</label>
<input type="text" id="email" name="email" placeholder="Your E-mail adress..."> <span class="error">* <?php echo #$emailErr;?></span>
<label for="message">Your message</label>
<textarea id="message" name="message" placeholder="Write your message here / the reason why you want to contact us " ></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<?php
$nameErr = $emailErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}?>
<div class="container33">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="thwid" method="post" target="">
<label for="fname">Full Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your full name..." value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br>
<label for="email">Your E-mail</label>
<input type="text" id="email" name="email" placeholder="Your E-mail adress...">
<span class="error">* <?php echo $emailErr;?></span>
<br>
<label for="message">Your message</label>
<textarea id="message" name="message" placeholder="" ></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div>
Try this.
<?php
$nameErr = $emailErr = "";
$name = $email = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["firstname"]) && $_POST["firstname"] != "") {
$name = test_input($_POST["firstname"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
echo $nameErr;
}
} else {
$nameErr = "Name is required";
echo $nameErr;
}
if (isset($_POST["email"]) && $_POST["email"] != '') {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
echo $emailErr;
} else {
$emailErr = "Email is required";
echo $emailErr;
}
if (isset($_POST["comment"]) && $_POST["comment"] != '') {
echo $comment;
$comment = test_input($_POST["comment"]);
} else {
$comment = "";
echo $comment;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}?>
You need to echo the value if you get any error.
Tip : Always use isset to check if the value is set or not. Also do the same in your email function.
so I got hosting, installed wordpress on it, and I put my html on it, it contains contact form written in html and it has separate php file with process. Main file which is accessed when you come to website is "front-page.php" which gets elements and it works, but after I submit form, I redirects me to www.mywebsite.com/front-page.php instead of www.mywebsite.com and i get error in line 2 which worked before, it is line " , what should I do, how to fix this? Adding code
<?php
// define variables and set to empty values
$name_error = $email_error = $message_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message_error = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $message_error == '' and $url_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'ignas.levinskas#mail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
echo("<script> window.location.href='../front-page.php'</script>");
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<form id="contactform" method="post" action="http://li-designs.com/wp-content/themes/vcs-starter/assets/app.php" >
<input name="name" type="text" class="feedback-input" placeholder="Name" required/>
<span class="error"><?= $name_error ?></span>
<input name="email" type="text" class="feedback-input" placeholder="Email" required/>
<span class="error"><?= $email_error ?></span>
<textarea name="message" type="text" value="<?= $message ?>" class="feedback-input" placeholder="Message" ></textarea>
<span class="error"><?= $message_error ?></span>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Send</button>
</form>
Have you tried using header in the post method?
header('location': 'www.mywebsite.com');
In normal PHP it redirects you to that URL.
I am trying to make an HTML form work.
My frontend code is this:
<form action="/form_validation.php" target="_blank">
<p><input class="w3-input w3-padding-16" type="text" placeholder="name" required name="name"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="email" required name="email"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="subject" required name="subject"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="comment" required name="comment"></p>
<p>
<button class="w3-button w3-light-grey w3-padding-large" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>
<p><?php echo $feedbackmsg;?></p>
and the file form_validation.php contains this:
<?php
$nameErr = $emailErr = $commentErr = $subjectErr = "";
$name = $email = $comment = $subject = "";
$feedbackmsg = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "*Name is required";
} else {
$name = validate($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "*Only letters and white space allowed";
}
}
if (empty($_POST["subject"])) {
$subjectErr = "*Subject is required";
} else {
$subject = validate($_POST["subject"]);
if (!preg_match("/^[a-zA-Z ]*$/", $subject)) {
$SubjectErr = "*Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "*Email is required";
} else {
$email = validate($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "*Invalid email format";
}
}
if (empty($_POST["comment"])) {
$commentErr = "*Write Me something";
} else {
$comment = validate($_POST["comment"]);
}
if (empty($nameErr) && empty($emailErr) && empty($commentErr)) {
$to = "myEmail#gmail.com";
$subject = $name;
mail($to, $subject, $comment, $email);
$feedbackmsg = "Your message has sent,<br> thanks";
}
}
}
So when action triggered returns back a blank page with the following url with my summury:
mysite.com/form_validation.php?name=anastasios&email=myemail%40hotmail.com&subject=mysubject&comment=ena+dio+ena+dio
I think this shoyld be normal. but why I dont have any email if it works properly?
Any thoughts? thanks a lot
All of your logic is wrapped in this condition:
if ($_SERVER["REQUEST_METHOD"] == "POST")
And this condition (as well as subsequent conditions therein, if the code got to them) is false because you're using GET instead of POST. Specify the POST method in your form:
<form action="/form_validation.php" target="_blank" method="post">
Before I get into it I would like to say that this did send emails from my local server so I have everything set up. After adding this form validation it no longer sends emails or shows errors. It just refreshes the page. I'm new to php coding so I'm sure I just have an if statement in the wrong order or something like that.
HTML
<section id="contact">
<h1 class="section-header">Contact Us Directly</h1>
<h4 class="text-center">Have any quesitons not answered in the <span>Questions Page</span>.</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" value="<?php $firstname ?>" placeholder="Your name.." tabindex="1" autofocus>
<span class="error"><?php $firstname_error ?></span>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" value="<?php $lastname ?>" placeholder="Your last name.." tabindex="2">
<span class="error"><?php $lastname_error ?></span>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php $email ?>" placeholder="Your email.." tabindex="3">
<span class="error"><?php $email_error ?></span>
<label for="message">Message</label>
<textarea id="subject" name="message" value="<?php $message ?>" placeholder="Write something.." style="height:200px" tabindex="4"> </textarea>
<span class="error"><?php $message_error ?></span>
<input type="submit" value="Submit" tabindex="5">
<span class="success"><?php $success ?></span>
</form>
</section>
PHP
<?php
$firstname_error = $lastname_error = $email_error = $message_error = "";
$firstname = $lastname = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstname_error = "First name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastname"])) {
$lastname_error = "Last name is required";
} else {
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$EmailFrom = localhost;
$EmailTo = "testrepairmail69#gmail.com";
$Subject = "New Order From tabletscreenfixer.com";
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Your Code is begging for some improvements as #R Smith mentioned; nevertheless this version works; i have tested on my pc.
<?php
$firstname_error = $lastname_error = $email_error = $message_error = "";
$firstname = $lastname = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstname_error = "First name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastname"])) {
$lastname_error = "Last name is required";
} else {
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
// var_dump($_POST); exit();
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$EmailFrom = "test#gamil.com";
$EmailTo = "tabletscreenfixer.com";//-> the message will be sent to this address if you have configure mail stuff well
$Subject = "New Order From tabletscreenfixer.com";
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}else{
echo "Failure";
}
}else{
echo "Failure 2";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<section id="contact">
<h1 class="section-header">Contact Us Directly</h1>
<h4 class="text-center">Have any quesitons not answered in the <span>Questions Page</span>.</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" value="<?php echo $firstname ?>" placeholder="Your name.." tabindex="1" autofocus>
<span class="error"><?php echo $firstname_error ?></span>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" value="<?php echo $lastname ?>" placeholder="Your last name.." tabindex="2">
<span class="error"><?php echo $lastname_error ?></span>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php echo $email ?>" placeholder="Your email.." tabindex="3">
<span class="error"><?php echo $email_error ?></span>
<label for="message">Message</label>
<textarea id="subject" name="message" value="<?php echo $message ?>" placeholder="Write something.." style="height:200px" tabindex="4"> </textarea>
<span class="error"><?php echo $message_error ?></span>
<input type="submit" value="Submit" tabindex="5">
<span class="success"><?php $success ?></span>
</form>
</section>
</body>
</html>
EDIT: Missing echo in the input value attribute;
Hope it helps;
Add some debugging. For example, everywhere you have an error, increment a error counter. Something like this:
if (empty($_POST["email"])) {
$email_error = "Email is required";
$errors++;
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
Then, at the end, instead of the long if condition:
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
You can use something like:
if ($errors == 0){
Which indicates no errors. Then, inside that if, when you try to send the mail, check for failure:
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}
else {
echo "The mail command failed!!";
}
Finally, give yourself some sort of indicator that there were errors, just for your testing phase. You can remove this else (or even add better styling and keep it):
if ($errors == 0){
// snip - lines of code in here removed to keep this snippet readable. this is your test and send mail logic.
}
else {
echo "You've got $errors errors! You need to correct them!";
}
With these changes, you should be able to find your issues quickly. As I said, you can also remove some of this code (like the echo statements) once you've finished your debugging.
Good luck!
Can anyone help me stop blank emails from being sent each time the page is viewed?
Here is the code I am using.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = "";
$name = $email = $gender = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = test_input($_POST["comment"]);
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = "Please leave a comment.";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//create the body of the email
$body = "Name: {$_POST['name']}
\n\nEmail: {$_POST['email']}
\n\nComments: {$_POST['comment']}";
$body = wordwrap($body, 70);
// The mail function
mail('email#email.com', 'Contact Us Submission', $body, "From: {$_POST['email']}");
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" class="text" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br>
Email: <input type="text" name="email" class="text" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br>
Comment: <textarea name="comment" rows="3" cols="20"><?php echo $comment;?></textarea>
<span class="error">* <?php echo $commentErr;?></span><br>
<input type="submit" name="submit" value="Submit" class="submit">
<?php
//if everything is ok, print the message:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($name && $email && $comment) {
echo "<p>Thank you, <b>$name</b>, for contacting us.</p>
<p> We will email you back at <i>$email</i> in a couple days.</p>\n";
} else { //missing form value.
echo '<p class="error">Please go back and fill out the form again.</p>';
return false;
}
}
?>
</form>
Put all of your form logic inside of your if ($_SERVER["REQUEST_METHOD"] == "POST") { statement. Not just the validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = test_input($_POST["comment"]);
if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
$commentErr = "Please leave a comment.";
}
}
//create the body of the email
$body = "Name: {$_POST['name']}
\n\nEmail: {$_POST['email']}
\n\nComments: {$_POST['comment']}";
$body = wordwrap($body, 70);
// The mail function
mail('email#email.com', 'Contact Us Submission', $body, "From: {$_POST['email']}");
}
FYI, you are wide open to header injections. That's something you should address before publishing this code to production.