I have a simple contact form. Works great - except the several emails I get daily. Spam!! I want to add a simple verification question (such as 'Zebras are black and...') where only a certain answer its accepted or the form will not be sent. How do I go about this?
The antispam isnt working at all!
Html:
<form action="submit.php" class="col4" method="post">
<p>Your name: <input name="name" type="text" size="100" />
</p>
<p>Your email: <input name="email" type="text" size="100" /> </p>
<p><input name="website" type="text" class="website"/></p>
<p class="antispam">Leave this empty: <input type="text" name="url" />
</p>
<p>Message: <textarea name="message" cols="100"></textarea>
</p>
<p><input type="submit" value="Send" /></p>
</form>
CSS:
form .website{ display:none; } /* hide because is spam protection */
PHP:
<?php
# spam protection
if (isset($_POST["website"]) && $_POST["website"] == "") {
# your php code to mail here
} else {
http_response_code(400);
exit;
}
// if the url field is empty
if (isset($_POST['url']) && $_POST['url'] == '') {
// put your email address here
$youremail = 'admin#napleswebgraphics.com';
// prepare a "pretty" version of the message
$body = "This is the form that was just submitted<br />
:
Name: $_POST[name]
E-Mail: $_POST[email]
Message: $_POST[message]";
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if ($_POST['email'] && !preg_match("/[\r\n]/", $_POST['email'])) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'Contact Form', $body, $headers);
} // otherwise, let the spammer think that they got their message through ?>
<h1 align="center">Thank You!</h1>
<div align="center">I'll get back to you as soon as possible! Click here to go back to the main page.
</div>
I want a specific answer to be the ONLY thing that allows the form to go through.
Adding this check is very simple. In your form html, add a new field:
<p>Zebras are black and...: <input name="animal" type="text" /></p>
Then, in your PHP you can check for its existence and bail early if it's wrong. Add this to the top of your PHP file:
if (empty($_POST['animal']) || $_POST['url'] !== 'white') {
http_response_code(400);
die('wrong answer');
}
Related
im using this contact form below. When I was running it on my local machine it was working. But on my server if the form fails it does the right thing and goes to fail.php but when all the fields are filled it goes to send_contact2.php after clicking send instead of success.php
This is the send_contact2.php
if (empty($_POST['name'])
|| empty($_POST['number'])
|| empty($_POST['email'])
|| empty($_POST['messagearea'])
){
header('Location: fail.php');
}
else {
$name = $_POST['name'];
$number = $_POST['number'];
$email = $_POST['email'];
$messagearea = $_POST['messagearea'];
$to = 'example#gmail.com';
$subject = "Website Message: Contact form";
$message = '$messagearea';
$headers = "From: WebsiteMessage";
mail($to, $subject, $message, $headers);
header("Location: success.php");
}
?>
This is my form
<form name="form1" method="post" action="send_contact2.php">
<input name="name" type="text" placeholder="Your Name"/> <br/>
<input name="email" type="email" placeholder="Your Email"/> <br/>
<input name="number" type="tel" placeholder="Your Number"/> <br />
<textarea name="messagearea" cols="" rows="" id="messagearea" placeholder="Your Message"/></textarea> <br/>
<input name="sumbit" type="submit" value="SEND" id="button2" />
</form>
I have this setting in my cPanel
Any help would be greatly appreciated
if the page stay on send_contact2.php it is because, header("Location: success.php") do not redirect. read this post, it could help. Php header location redirect not working
In my opinion PHP must be outputing some text (char, error or warning?) or you have used a char before <?php in your send_contact2.php file. That's why header is not working. Remember that header() must be called before any actual output is sent.
OP here, managed to sort it in the end
Was a mail server issue, so if anyone in the future gets this problem check your php settings on your hosting and make sure it allows mail() and make sure you set up an email address where you're sending the email to on your server.
thanks to everyone that helped me debug
I thought it would be easy (silly, I know) and so I followed the instructions I found at this site for a PHP email form: http://www.html-form-guide.com/email-form/dreamweaver-email-form.html I didn't need help with the Dreamweaver interface at all, I just needed the script, and I knew (or thought I knew) how to adapt their simple form into the form I needed, and adapt the script accordingly.
The form in question may be found at this URL: http://nineinchbride.com/SuitedForWar_BookTwo_PreOrderForm.php
The code as it presently exists on the page is as follows:
<form id="PreOrder_Book_2" name="PreOrder_Book_2" method="post" action="">
<p>Your Name:
<input type="text" name="CustomerName" id="CustomerName" />
</p>
<p>Your Email:
<input type="text" name="CustomerEmail" id="CustomerEmail" />
</p>
<p>
<input type="checkbox" name="NotifyPaperback" id="NotifyPaperback" />
Notify me when paperback is available.</p>
<p>
<input type="checkbox" name="Notify_eBook" id="Notify_eBook" />
Notify me when eBook is available.</p>
<p>Desired eBook Format:</p>
<p>
<label>
<input type="radio" name="eBookFormats" value=".mobi" id="eBookFormats_0" />
.mobi (Kindle)</label>
<br />
<label>
<input type="radio" name="eBookFormats" value=".epub" id="eBookFormats_1" />
.epub (Nook / Ipad / Sony / Kobo)</label>
<br />
<label>
<input type="radio" name="eBookFormats" value=".pdf" id="eBookFormats_2" />
.pdf (All readers)</label>
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
<br />
</p>
</form><script>
function validateForm()
{
var name=document.forms["PreOrder_Book_2"]["CustomerName"].value;
if (name==null || name=="")
{
alert("Name cannot be left blank.");
return false;
}
var z=document.forms["PreOrder_Book_2"]["CustomerEmail"].value;
if (z==null || z=="")
{
alert("Please enter your email.");
return false;
}
}
</script>
<script><?php
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['CustomerName'];
$visitor_email = $_POST['CustomerEmail'];
$message = $_POST['NotifyPaperback'];
$message = $_POST['Notify_eBook'];
$message = $_POST['eBookFormats'];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
$email_from = 'webmanager#nineinchbride.com';//<== Put your email address here
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
"email address: $visitor_email\n".
"Here is the message:\n $message".
$to = "webmanager#nineinchbride.com";//<== Put your email address here
$headers = "From: $email_from \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: http://nineinchbride.com');
?></script>
Please bear in mind that while I know my way around code a bit (enough to adapt things a little, adjust naming for consistency and the like), I am not a programmer per se, so please go easy on me.
Update 1:
Okay, I'm making progress here. I made the following changes to the PHP:
$name = $_POST['CustomerName'];
$visitor_email = $_POST['CustomerEmail'];
$message1 = $_POST['NotifyPaperback'];
$message2 = $_POST['Notify_eBook'];
$message3 = $_POST['eBookFormats'];
//Validate first
if(empty($name)||empty($visitor_email))
{
echo "Name and email are mandatory!";
exit;
}
$email_from = 'webmanager#nineinchbride.com';//<== Put your email address here
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
"email address: $visitor_email\n".
"Notify When Paperback Is Available: $message1\n".
"Notify When eBook Is Available: $message2\n".
"My eBook Format Is: $message3\n".
And, hurray, I'm getting all the form data. Figured it out for myself too ;-)
However, none of the validation is working. And the re-direct after successful submission is not working either. Any idea what's up with that?
Update 2:
Wow, validation problem solved, thank you Poria! I just added
<input type="button" name="button" id="button" value="Submit" onclick="return validateForm();"/>
to the form itself in place of the submit button I had before, and now the front end validation is working. Great!
But now the form itself does not submit any longer! What did I do wrong?
Your first mistake is
$message = $_POST['NotifyPaperback'];
$message = $_POST['Notify_eBook'];
$message = $_POST['eBookFormats'];
change it to
$message = $_POST['NotifyPaperback'];
$message .= $_POST['Notify_eBook'];
$message .= $_POST['eBookFormats'];
not the dot(.) for concatenation.
Secondly you never called the validation function
change the button like this
<input type="button" name="submit" id="button" value="Submit" onclick="return validateForm();"/>
Now form will be submit.
Hope it helps!
For further questions please post another question.
I've been working on websites for a while now and I keep running into this issue with my contact forms.
So I make sure that I include the "required" on contact forms, and if the form isn't filled out, it's great. It makes sure that the user puts information into the fields for the information to be sent.
However, on iOS that is not the case. Those required tags get ignored, so I constructed my PHP to ensure that the inputs were still required.
Hopefully someone can help me out.
Here is the HTML contact form:
<input type="text" name="phone" class="phoneInput" autocomplete="off" placeholder="What phone number can we reach you at? (Optional)" /><br />
<input type="email" name="email" class="emailInput" autocomplete="off" placeholder="What is your primary e-mail address?" required /><br />
<textarea name="message" id="message" autocomplete="off" placeholder="How may we assist you?" required></textarea><br />
<div class="submit">
<input type="submit" value="SEND MESSAGE" id="button"/>
<div class="ease"></div>
</div>
</form>
updated PHP:
<?php
// Name of sender
$name=$_GET["name"];
// Phone number of sender
$number=$_GET["phone"];
// Mail of sender
$mail_from=$_GET["email"];
// Message
$message=$_GET["message"];
// Subject
$subject= "Someone has sent you a message from your contact form!";
// Message Headers
$headers = 'From: ' .$name."\r\n". 'Reply-To: ' . $mail_from."\r\n" . 'Callback Number: '.$number."\r\n";
// E-mail to:
$to ='shawn#synergycomposites.net';
// Empty variables, tests to see if any of the fields are empty
$emptyName = empty($name);
$emptyEmail = empty($mail_from);
$emptyMessage = empty($message);
// Perform if tests to see if any of the fields are empty, and redirect accordingly
if ($emptyName == true) {
header ("location:/#modalFailure");
} else {
if ($emptyEmail == true) {
header ("location:/#modalFailure");
} else {
if ($emptyMessage == true) {
header ("location:/#modalFailure");
} else {
header ("location:/#modalSuccess");
mail($to, $subject ,$message, $headers);
}
}
}
?>
Your calling the mail() function before checking the fields. This function actually sends the email. The return variable $send_contact is just a Boolean whether the function succeeded or not. Something like this should work:
if(empty($name) || empty($mail_from) || empty($message)) {
header('location:/#modalFailure');
} else {
$mail_sent = mail($to, $subject ,$message, $headers);
if(!$mail_sent) {
header("location:/#modalFailure");
} else {
header("location:/#modalSuccess");
}
}
This code will run into issues if the form submits non-empty strings. For instance this " " instead of "" or NULL. It would also be advisable to add filtering and validation to this code.
( on another note you may want to use $_POST instead of $_GET for form submissions.)
I have a form that I am trying to add some steps that will minimize spam without forcing the end user to input some random number text series.
here’s an example of my form code:
<form action="form.php" method="post">
<label for="Name" style="some style">Enter your name:</label>
<input type="text" name="name">
<label for="Email" style="some style">Your email address:</label>
<input type="text" name="email">
<label for="City" style="some style">City:</label>
<select id="some ID" name="city" value="PQS" >
<option value="" selected disabled>Choose A City</option>
<option value="City1">City1</option>
<option value="City2">City2</option>
<input type="submit" value="Sign Up Now" class="button" id="subscribe">
</form>
<p id="error" style="some style">OOPS! Something went wrong. Please try again.</p>
<p id="success" style="some style">Success! We’ll contact you shortly</p>
My current form.php looks somewhat like this:
<?php
$emailmanager = 'me#myemail.com';
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$city = $_POST['city'];
error_reporting(0);
$email = trim($_POST['email']);
$Ok = ereg("^([a-zA-Z0-9_\.-]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+)) ([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", $email);
if ($Ok) {
mail($emailmanager,'New Contact Request','You have a new contact request for homes in '.$_POST['city'].' from '.$_POST['name'].' ','From: '.$_POST['email'].' ');
if( !ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$UNameFrm) )
{
echo 1;
}
}
else
{
echo 0;
}
What I am trying to incorporate is a blank field that can deter the spambots, and I found an awesome code to use but I would like to incorporate it into my code above. See below the code i found:
<?php
// if the url field is empty
if(isset($_POST['url']) && $_POST['url'] == ''){
// put your email address here
$youremail = 'you#yoursite.com';
// prepare a "pretty" version of the message
$body = "This is the form that was just submitted:
Name: $_POST[name]
E-Mail: $_POST[email]
Message: $_POST[message]";
// Use the submitters email if they supplied one
// (and it isn't trying to hack your form).
// Otherwise send from your email address.
if( $_POST['email'] && !preg_match( "/[\r\n]/", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
// finally, send the message
mail($youremail, 'Contact Form', $body, $headers ); } // otherwise, let the spammer think that they got their message through ?>
This code i found requires me to create a class
.antispam { display:none;}
...and add some html in my form
<label for="url" class="anti spam">Leave This Empty:</label>
<input type="text" name="url" />
how do I incorporate these 2 together? There are some things that are obvious to me, like adding
$url = $_POST['url'];
to my form.php on the next line following $city. My challenge is where to incorporate
// if the url field is empty
if(isset($_POST['url']) && $_POST['url'] == '')
and
if( $_POST['email'] && !preg_match( "/[\r\n]/", $_POST['email']) ) {
$headers = "From: $_POST[email]";
} else {
$headers = "From: $youremail";
}
into my form.php without screwing up my form function entirely. Any help would be appreciated, and I hope I made my question clear
You generate a random token for each guest session (or even user's login or form page) and save in database.
When printing forms, add one hidden input.
<input type="hidden" name="token" value="token_value_RANDOM1234567890">
When user submits form, then you check if given token is valid (or belongs to authenticated user, in login case). If belongs, then he's a valid user, else is a bot (not so simple as that). By the way, it complicates the process of spamming, do not block all ways of spamming. And you get an improvement on your website security.
Hope it helps.
You should put the class on the input, not the label, since labels aren't sent to the server.
<input type="text" class="antispam" name="antispam" value="">
Browsers won't send inputs that have display: none;, so if you receive this input, it means it came from an automated spammer.
if (isset($_POST['antispam'])) {
// Reject as spam
}
I use this honeypot tactic all the time. The trick is to create a field on the form that will not be visible to humans with eyes, but will be seen by bots. I usually give it an attractive name like "url" like your example does.
<input class="honeypot" name="url" value="url" />
Then you use CSS to push it off the screen:
input.honeypot {
position:absolute;
left:-5000px;
}
That can go anywhere in your stylesheet, or in a <style> tag in your html, or right on the input
<input style="position:absolute; left:-5000px;" name="url" value="url" />
Then you need a test in the validation code which is the action PHP:
if (isset($_POST['url'] && 'url' != $_POST['url']) {
header("location:/routing-error");
}
This gives the bot a 404 for the page "routing-error"
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to stop form from sending email more times after initial success.
First of all, i have structured my website using directories. So basically every page is a directory and in that directory, i have a file called index.php.
I have four contact forms on my site, and at the moment, the seem to all work using the hnadler.php file. The handler file validates the data, checks the form-id posted and based on that, it routes the email appropraitely. A success message is displayed if successfully sent. However, my current implimentation is flawed in that if the user refreshes, another mail is sent. How can i solve this with my existing code? Thank you
//handler.php
<?php
if(isset($_POST['submit'])) {
//carry out validation
if(!isset($hasError)) {
//check the form id posted and set email address in $emailTo accordingly
$body = "Name: $name \n\nEmail: $email \n\nEnquiry: $enquiry";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
//index.php
<?php if(isset($hasError)) { ?>
<p class="error">Please make sure you have filled all fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<p><strong>Your enquiry was sent successfully.</strong></p>
<p>Thank you for your enquiry! Your email was successfully sent and we will be in touch with you promptly.</p>
<?php }; ?>
<form id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Enquiry form</legend>
<label for="name">Name:</label><input type="text" size="50" name="name" id="name" value="" class="required" />
<label for="email">Email:</label><input type="text" size="50" name="email" id="email" value="" class="required email" />
<label for="enquiry">Enquiry:</label><textarea rows="5" cols="20" name="enquiry" id="enquiry" class="required"></textarea>
<input type="submit" name="submit" value="Submit enquiry" class="curved-btn"></input>
<input type="hidden" id="form-id" name="form-id" value="general"></input>
</fieldset>
</form>
?>
The problem is that you aren't actually submitting to handler.php because of this:
<form id="contactform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Change it to this:
<form id="contactform" method="post" action="handler.php">
And put your send e-mail code inside of handler.php. You will also need to put a redirect in there to get them back to a page. There are other ways to go about this, but this is how I would do it.
The browser will/can repost the data on refresh, so it will look like a new request.
A quick fix is to redirect after the form submission:
header("Location: success.php");
That way if the refresh they refresh the success page, not the page you posted to.