I used the mail function to do a contact form and it all works fine. However, I just noticed that after sending an email, every time a refresh the page, even though the fields are empty, an email keeps being sent.
My code looks like this:
<form role="form" method="POST">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers optional/headers
$headers .= "From:$from";
// 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 mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
echo $result;
}
}
}
?>
</form>
How can I make the site forget all the details from the input fields once an email is sent?
I tried to follow this question here but I don't seem to be able to make it work on my site
The easiest way is to add an forwarding in your code, like that:
EDIT: at #CD001 commentary
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
// header('Location: ?successfull-submit'); exit; // this one would fail because above is an output.
echo '<meta http-equiv="refresh" content="0; url=?successfull-submit">'; // its not a good /nice alternative but it "works".
Redirect to ?sent=1 without sending any output. And check 'sent' to determine whether or not to display the success message. Try below (assuming your script is contact.php). Also make sure
contact.php
<?php
$result = '';
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers optional/headers
$headers .= "From:$from";
// 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 mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
//$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
//echo $result;
header('Location:' . 'contact.php?sent=1');
exit;
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
//echo $result;
}
}
}
if(isset($_GET['sent'])) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
}
echo $result;
?>
<form role="form" method="POST">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
try like this,in your success message part..
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers optional/headers
$headers .= "From:$from";
// 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 mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
echo "<script>alert('Mail sent Successfully');</script>";
echo "<script>window.location = 'contact.php';</script>";
} else {
echo "<script>alert('Mail not sent');</script>";
echo "<script>window.location = 'contact.php';</script>";
}
}
}
?>
while redirect to another page you can restrict that duplication problem....
Just try redirecting to another page or another function that discards the old $_POST data.
You could use session variable and reset it after each request.
Or, prevent reloading same page using javascript.
Or, redirect to some other page upon completion (if possible)
You can try to add CSRF token to your page to prevent double submission.
Refer to this link: How to prevent multiple form submission on multiple clicks in PHP
When the user refreshes the page, it is possible that the same parameters are getting posted again. As a result, if (isset($_POST["submit"])) This condition becomes true and mail will be sent every time user reloads.
One solution is to redirect to the same page or to a different page on success full completion.
ie,
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
}
Instead of the above method, redirect user to the same page or different page and show a message there. If you want to show the same page you can redirect with a flag in the query string as ?show_success_msg= true.
Then do this.
if(isset($_GET['show_success_msg']) && $_GET['show_success_msg'] == 'true') {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
}
Complete solution here:
<?php
// Handle PHP code always on Top of the page (ie, Not after your HTML), You cant send headers if you have any content above it.
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$subject_line = $_POST['subject'];
$situation = $_POST['situation'];
$from = 'myemail#email.co.za';
$to = 'myemail#email.co.za';
$subject = 'SchoemanLaw lead ...';
$body ="From: $name <br/> E-Mail: $email <br/> Mobile: $mobile Subject: $subject_line <br/> Situation: $situation";
//$body ="From: $name\r\n E-Mail: $email\r\n Mobile:\r\n $mobile Subject: $subject_line\r\n Situation:\r\n $situation";
// set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers optional/headers
$headers .= "From:$from";
// 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 mobile has been entered
if (!$_POST['mobile']) {
$errMobile = 'Please enter your number';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMobile) {
if (mail($to,$subject,$body,$headers)) {
$result='<div class="alert alert-success">Thank You ! We will be in touch soon</div>';
echo $result;
} else {
header("Location: your_page.php?show_success_msg=true")
}
}
}
?>
<form role="form" method="POST">
<?php if(isset($_GET['show_success_msg']) && $_GET['show_success_msg'] ==
'true') {
$result='<div class="alert alert-success">Thank You ! We will be in touch
soon</div>';
echo $result;
} ?>
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Contact a Conveyancing Property Lawyer Now</h3>
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="email" name="email" placeholder="Email" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Contact Number" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> required>
</div>
<div class="form-group">
<select name="situation" id="situation">
<option>Select Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary">Submit</button>
Related
Im trying to build a simple contact form for a Wordpress site. I want it to send an email and reload the contact page it was sent from with an error/success message.
I have installed WP mail SMTP and it sends the test email.
Now to the problems. I have a form in html that I want to use. This form has been put in a custom template.
The php is borrowed from guides I have found online and I have used several of them. None of them work for me. When I hit the submit button the page loads the base template (not the custom template that I'm using for the form page) and no mail is sent. I want it to load the same page but with an error/success div telling me what happened. If I run the php before pressing submit it gives me the error message.
Here is my php:
if(isset($_POST['submitButton'])){
//response generation function
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $reason){
global $response;
if($type == "success") $response = "<div class='success'>{$reason}</div>";
else $response = "<div class='error'>{$reason}</div>";
}
//response messages
$not_human = "Human verification incorrect.";
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//user posted variables
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$phone = $_POST['phone'];
$human = 2;
//php mailer variables
$to = get_option('admin_email');
$subject = "Someone sent a message from ".get_bloginfo('name');
$headers = 'From: '. $email . "\r\n" .
'Reply-To: ' . $email . "\r\n";
if(!$human == 0){
if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
else {
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
my_contact_form_generate_response("error", $email_invalid);
else //email is valid
{
//validate presence of name and message
if(empty($name) || empty($message)){
my_contact_form_generate_response("error", $missing_content);
}
else //ready to go!
{
$sent = mail($to, $subject, strip_tags($message),
$headers);
if($sent) my_contact_form_generate_response("success",
$message_sent); //message sent!
else my_contact_form_generate_response("error",
$message_unsent); //message wasn't sent
}
}
}
}
else if ($_POST['submitted'])
my_contact_form_generate_response("error", $missing_content);
}
?>
Here is my html for the "print error/success" and the form:
<?php echo $response; ?>
<form class="interest-form" action="<?php the_permalink(); ?>" method="POST">
<fieldset>
<legend>Anmäl Intresse:</legend>
<div class="row">
<div class="col-6">
<input type="text" class="form-control" placeholder="Namn" name="name" value="<?php echo esc_attr($_POST['name']); ?>">
</div>
<div class="col-6">
<input type="tel" class="form-control" placeholder="Telefonnummer" name="phone" value="<?php echo esc_attr($_POST['phone']); ?>">
</div>
</div>
<div class="row">
<div class="col">
<input type="email" class="form-control" placeholder="E-post" name="email" value="<?php echo esc_attr($_POST['email']); ?>">
</div>
<div class="col">
<input class="form-control" type="text" placeholder="<?php the_field('fb_8_1_plats'); ?> <?php the_field('fb_8_1_startdatum'); ?>" readonly name="plats_datum">
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="meddelande1">Meddelande:</label>
<textarea class="form-control" rows="3" name="message" value="<?php echo esc_attr($_POST['message']); ?>" id="meddelande1"></textarea>
</div>
</div>
</div>
<input type="hidden" name="submitted" value="1">
<button type="submit" name="submitButton" class="btn btn-primary float-right">Skicka intresseanmälan</button>
</fieldset>
</form>
I really can't figure out what is wrong, I spent two full days just googling, trying and failing last weekend. After that I gave up and haven't looked at at for a week. Please help!
Edit: It doesn't load index.php, the path is still the same but it uses the template for index.php
When I submit the form, I get the statement "No arguments Provide!" however, I have a second website running the same exact form and it completely works. The php file is from the Bootstrap Agency template. Here is the code
HTML
<div class="span9">
<form id="contact-form" class="contact-form" action="contact.php">
<p class="contact-name">
<input id="name" type="text" placeholder="Full Name" value="" name="name" />
</p>
<p class="contact-email">
<input id="email" type="text" placeholder="Email Address" value="" name="email" />
</p>
<p class="contact-phone">
<input id="phone" type="text" placeholder="Phone Number" value="" name="phone" />
</p>
<p class="contact-message">
<textarea id="message" placeholder="Your Message" name="message" rows="15" cols="40"></textarea>
</p>
<p class="contact-submit">
<li><input type="submit" value="Send Message" class="special" /></li>
<li><input type="reset" value="Reset" /></li>
</p>
<div id="response">
</div>
</form>
PHP
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'yourname#yourdomain.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Any help will be greatly appriciated.
After digging around for the file, I believe this is the one that works. Here is the code:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['subject']) ||
empty($_POST['message']))
/*
!filter_var($_['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
*/
if(empty($_POST['name'])) {
echo "Please enter your name."; return false;
}
elseif(empty($_POST['email'])) {
echo "Please enter your email."; return false;
}
if(empty($_POST['message'])) {
echo "Please enter your message."; return false;
}
elseif(empty($_POST['subject'])) {
echo "Statement if there is an error"; return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'youname#yourdomain.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $subject";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
You are missing method="post" in your form.
<form id="contact-form" class="contact-form" action="contact.php" method="post">
The default method when sending in a form is GET.
So you need:
<form method='post' id="contact-form" class="contact-form" action="contact.php">
I have no real experience with PHP, and so have just pulled bits of code from various answers to help construct a simple PHP contact form. I have spent two days trying to work out why various variations aren't working. I've included my code:
HTML :
<section class="form-section" id="form-section">
<div class="row headline">
<h3>Free Quotation</h3> </div>
<div class="row">
<form action="mailer.php" method="post" name="htmlform" class="contact-form" target="_blank">
<div class="col span-1-of-2">
<div class="row inputs">
<label for="name">Name</label>
<input name="name" placeholder="Your name" required="" type="text"> </div>
<div class="row inputs">
<label for="email">Email</label>
<input name="email" placeholder="Your email" required="" value="" type="email" class="required email"> </div>
<div class="row inputs">
<label for="business_name">Business Name</label>
<input value="" name="business_name" placeholder="Your business name" required="" type="text" class=""> </div>
</div>
<div class="col span-1-of-2 message-box-container">
<label class="text-box-label" for="message">In a few words, what are you looking for?</label>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<div class="row form-messages">
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try again</div>";
}
?> </div>
<div class="col span-2-of-3">
<div class="clear">
<input type="submit" value="Find Out More" name="subscribe" class="button"> </div>
</div>
</form>
</div>
</section>
This is my mailer.php form:
<?php
// Get the form fields, removes html tags and whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$business_name = strip_tags(trim($_POST["business-name"]));
$business_name = str_replace(array("\r","\n"),array(" "," "),$business_name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check the data.
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
// Set the recipient email address. Update this to YOUR desired email address.
$recipient = "chussell#thegreenbuddha.co.uk";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_content .= "Business Name: $business_name \n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
mail($recipient, $subject, $email_content, $email_headers);
// Redirect to the index.html page with success code
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=1#form");
?>
When I have this on live preview both success and error messages display with PHP code. I have the file saved as a index.php. And when I submit it opens up the fresh page which is blank.
When I've added the new index.php and mailer.php to my cpanel, my website no longer displays!
Any suggestions or improvements?
Many thanks!
The following
<?php
if($_GET['success'] == 1) {
echo "<div class="success">Thank You! We'll aim to follow up as soon as possible</div>";
}
if($_GET['success'] == -1) {
echo "<div class="error">Oops something went wrong, please try gain</div>";
}
?>
Into
<?php
if($_GET['success'] == 1) {
echo '<div class="success">Thank You! We\'ll aim to follow up as soon as possible</div>';
}
if($_GET['success'] == -1) {
echo '<div class="error">Oops something went wrong, please try gain</div>';
}
?>
The following
if (empty($name) empty($business_name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Into
if (empty($name) || empty($business_name) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: http://www.thegreenbuddha.co.uk/index.php?success=-1#form");
exit;
}
Please change the following also:
$business_name = strip_tags(trim($_POST["business-name"]));
Into
$business_name = strip_tags(trim($_POST["business_name"]));
I'm a front end developer and I'm new to PHP. I'm building a contact form for my site using BootStrap3, while the form actually submits the message and I'm able to receive the sent message in my gmail inbox, some of the PHP tags show as plain text in the modal form. How do I make the error messages appear as text, instead of polluting the form with PHP tags?
The Boottrap3 form:
<form class="form-horizontal" role="form" method="post" action="index.php">
<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" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?><!-- shows all the time as code-->
</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" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?><!-- shows all the time as code-->
</div>
</div>
</form>
The PHP code (index.php)
<?php
if ($_POST["submit"]) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$human = intval($_POST['human']);
$from = 'Demo Contact Form';
$to = 'demo#test.com';
$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';
}
// 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>';
}
}
}
?>
Add at least if condition before you display the paragraph containing error message, e.g.:
<?php if ($errName) : ?>
<p class="text-danger"><?php echo $errName ?></p>
<?php endif; ?>
It should do the trick in your example.
And btw: your contact form should be provided as a PHP file. If it's an HTML file, it wont work because it wont get interpreted by PHP.
Try like this
<?php echo "<p class='text-danger'>".$errName."</p>";?>
So I have a HTML form with some PHP but I'm not getting any email whatsoever after submitting it. I can't find the problem! can you help me out?
Tried changing the if(isset($_POST['submit'])) { to 'enviar' but still not working.
tried putting some echos to see where it's not working. the only statement that is stopping at the else statement is stripslashes.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Before getting any email, you have to be sure the email is being sent.
$sent = mail($emailTo, $subject, $body, $headers);
var_dump($sent);
What does this code output when placed in the appropriate place?
Have you tried a simple php page to do a test Email (eg fixed content) and I assume the webserver has email configured and is prepared to relay for your address?
If this is WordPress contact form, for starters:
mail($emailTo, $subject, $body, $headers);
should be:
wp_mail($emailTo, $subject, $body, $headers);
See: wp_mail codex
Now you have to check your e-mail setup, as well as WordPress e-mail setup too.