Receiving Spam from my Form Using PHPMailer - php

I am coming to stackoverflow for this because everything I search pretty much talks about email from a form using PHPMailer going to a users spam box. But, I need info on receiving spam from the form itself. I use it on a small, very light traffic real estate agents website. She gets spam from time to time and I don't know how to resolve it. PHPMailer seems to be the go to tool for sending email with PHP, so I figure spam/security is pretty well covered. I must be doing something wrong.... I am using class.phpmailer.php of course, and here is my code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
if ($name == "" OR $email == "" OR $phone == "" OR $message == "") {
echo "You must specify a value for name, email address, phone, and message.";
exit;
}
foreach( $_POST as $value ){
if( stripos($value,'Content-Type:') !== FALSE ){
echo "There was a problem with the information you entered.";
exit;
}
}
if ($_POST["address"] != "") {
echo "Your form submission has an error.";
exit;
}
require_once("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
if (!$mail->ValidateAddress($email)){
echo "You must specify a valid email address.";
exit;
}
$email_body = "";
$email_body = $email_body . "Name: " . $name . "<br>";
$email_body = $email_body . "Email: " . $email . "<br>";
$email_body = $email_body . "Phone: " . $phone . "<br>";
$email_body = $email_body . "Message: " . $message;
$mail->SetFrom($email, $name);
$address = "email#domain.com";
$mail->AddAddress($address, "A Name Here");
$mail->Subject = "Message from " . $name . " on website contact form";
$mail->MsgHTML($email_body);
if(!$mail->Send()) {
echo "There was a problem sending the email: " . $mail->ErrorInfo;
exit;
}
header("Location: index.php?status=thanks");
exit;
}
The HTML is very simple:
<form id="form" name="form" method="post" action="contact-process.php">
<?php if (isset($_GET["status"]) AND $_GET["status"] == "thanks") { ?>
<p class="form-thanks">Thank you for contacting us. We'll be in touch with you very soon.</p>
<?php } ?>
<label>Name
<span class="small">First and Last</span>
</label>
<input type="text" name="name" id="name" />
<label>E-Mail
<span class="small">name#email.com</span>
</label>
<input type="text" name="email" id="email" />
<label>Phone Number
<span class="small">With area code</span>
</label>
<input type="text" name="phone" id="phone" />
<label>Message
<span class="small">How can we help you?</span>
</label>
<textarea cols="40" rows="8" name="message"></textarea>
<button type="submit">Submit</button>
<div class="spacer"></div>
</form>

A simple technique to avoid spam is to use something called a honey-pot, which is a text field which is not visible to normal users but a dumb spam-robot will probably enter something into that field.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// robot detection
$honeypot = trim($_POST["email"]);
if(!empty($honeypot)) {
echo "BAD ROBOT!";
exit;
}
$name = trim($_POST["name"]);
$email = trim($_POST["real_email"]);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
// rest stays as is
In your HTML file you need to insert another "hidden" text field which is the honeypot:
<label>E-Mail
<span class="small">name#email.com</span>
</label>
<input type="text" name="email" style="display: none;">
<input type="text" name="email_real" id="email" />
Note how I changed the name of the actual, visible email text field to "email_real". It would be even better to avoid the word "email" completely in the real email field, since many robots are dumb.
The invisible honeypot input field should be called "email" though. Why? Because most robots are scanning for some standard input fields like "email", "address" etc. - so it's important to give the honeypot a common form field name.
Another neat trick is to swap some common field names, i.e swap the name for email and zip fields, so robots will fill in a numeric value for the email address and an email address for the zip code which will fail the validation.
It's not a 100% guarantee to kill all spam but it worked quite well for me without forcing the user to solve an annoying captcha...

Related

PHP email script not sending all form fields

IF (I Started Receiving Spam Bot Forms)
THEN (I Implemented New PHP Email script using a basic Honey Pot Method)
$ERROR (New PHP is not sending ALL the forms fields. Upon sending the form, my email is only receiving the, textarea id="message", field)
$LOG_FILE (My previous PHP script implemented a dynamic catch-all solution for form fields)
$FAILED_SOLUTION (Conversely I attempted to add the individual, $phone & $address fields manually on lines #6 7 & 14 of the PHP but am still only receiving the, textarea id="message", field)
$NOTES (I am self taught & typically only deal with PHP on a need to know basis. Please try to keep it simple and include a step-by-step explanation. Feel free to suggest any "best practices" i may have overlooked unrelated to my problem!)
$QUESTION = "Can someone show me how to call the other form fields in the PHP script to send to my email?"
$SUCCESS = "Thanks in Advance For Any Help That Maybe Given!";
PHP:
<?php
if($_POST){
$to = 'your-email-here#gmail.com';
$subject = 'Contact Form Submission';
$name = $_POST['name'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$email = $_POST['email'];
$message = $_POST['message'];
$robotest = $_POST['robotest'];
if($robotest)
$error = "Spam Protection Enabled";
else{
if($name && $phone && $address && $email && $message){
$header = "From: $name <$email>";
if(mail($to, $subject, $message,$header))
$success = "Your message was sent!";
else
$error = "Error_36 there was a problem sending the e-mail.";
}else
$error = "Error_09 All fields are required.";
}
if($error)
echo '<div class="msg error">'.$error.'</div>';
elseif($success)
echo '<div class="msg success">'.$success.'</div>';
}
?>
HTML FORM:
<form method="post" action="Form_Email.php">
<input type="text" id="name" name="name" placeholder="name" required>
<input type="text" id="phone" name="phone" placeholder="phone" required>
<input type="text" id="address" name="address" placeholder="address" required>
<input type="text" id="email" name="email" placeholder="email" required>
<textarea id="message" name="message" placeholder="message" required> </textarea>
<p class="robotic">
<input name="robotest" type="text" id="robotest" class="robotest" autocomplete="off"/>
</p>
<input type="submit" id="SEND" value="Submit">
</form>
Your message contains only $_POST['message'] for now. If you want to append other values, use concatenation on your $message variable.
$message .= ($name . $phone . $address . $etc)
Notice: A $foo .= $bar construction stands for $foo = $foo . $bar.
Do not forget about whitesigns such as spaces or new lines wherever you want. Simply concatenate ' ' or "\n".
After that, just send a mail using your $message as message.

PHP Contact form to email [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I used this post to make a simple ‘contact us’ form. The form collects a few pieces of information (email, name and a message) from your visitor and emails it to you.
Instead of redirecting to a thank you page, I'd prefer it to just print the thank you (or error) text in the same HTML form page.
How can this be done? Where do I need to change to be able to keep the user in the same page and show the confirmation message ("Thank you")?
Edit: Found a much simpler way to do this - with ajax.
Here is my suggestion.
1- Change your file name contact-form.html to contact-form.php
2- Added include line and edit your form action in contact-form.php:
<h1>Contact us</h1>
<?php include './contact-form-handler.php'; ?>
<form method="POST" name="contactform" action="#">
3- Edit your contact-form-handler.php, disable header and added your thank you with personal message, you can also added some layout and decoration that is left to your fantasy.
//header('Location: contact-form-thank-you.html');
echo "Thank you " . $name . "<br />";
echo "We will contact you soon";
4- Last thing I will added condition to check if the form is submitted or not
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty... etc
}
5- (Optional) To re-fetch the posted values if failed I have added following to the form inputs (3 of them, each field got one with the respective field/variable name):
value="<?php if (isset($_POST['name'])) echo $name; ?>"
But in general When all this done, I will personally will go through the form and clean it up a little bit. Like if I am check the content in JavaScript it is not necessary to check if the fields are empty, so checking submission form is enough. I have not talk about form security yet against any kind of misuse, this just to make some thoughts when you come so far.
Complete code
Here is your final results, with extra things I done:
contact-form.php
<form method="POST" name="contactform" action="#">
<p>
<label for='name'>Your Name:</label> <br>
<input type="text" name="name" value="<?php if (isset($_POST['name'])) echo $name; ?>">
</p>
<p>
<label for='email'>Email Address:</label> <br>
<input type="text" name="email" value="<?php if (isset($_POST['email'])) echo $email_address; ?>"> <br>
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message" value="<?php if (isset($_POST['message'])) echo $message; ?>"></textarea>
</p>
<input type="submit" value="Submit"><br>
</form>
contact-form-handler.php
<?php
$errors = '';
$myemail = 'yourname#website.com';//<-----Put Your email address here.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message'])
)
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address)
)
{
$errors .= "\n Error: Invalid email address";
}
if (empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. " .
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
//redirect to the 'thank you' page
//header('Location: contact-form-thank-you.html');
echo "Thank you " . $name . "<br />";
echo "We will contact you soon";
$name = "";
$email_address = "";
$message = "";
}
}
?>

send html form with php can't solve

I have big problem with sending easy html form with php.
My problem is when all fields are empty it still send message.
I don't why this code still send empty form??
<form id="form1" name="form1" method="post" action="forma.php">
<p>
<label for="ime">Ime:</label>
<input type="text" name="ime" id="ime" />
</p>
<p>
<label for="prezime">Prezime:</label>
<input type="text" name="prezime" id="prezime" />
</p>
<p>
<label for="email">e-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p>
<label for="poruka">Poruka:</label>
<textarea name="poruka" cols="40" rows="10" id="poruka"></textarea>
</p>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
My php code:
<?php
if (isset($_POST['submit']))
{
$ime= $_POST['ime'];
$prezime= $_POST['prezime'];
$email= $_POST['email'];
$poruka= $_POST['poruka'];
$email_from = 'neki#email.com';
$email_subject = "forma sa sajta";
$email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ;
$to = "myemail#gmail.com";
mail ($to, $email_subject, $email_body);
echo "Message is sent";
}
else {
echo "Message is not sent";
}
?>
So again, when i fill fields message is sent. It is ok, i received email.
But when i just click submit (without filling fields) it still send message to my email.
What is wrong with this code? I try everything i know, but without success.
Thank you.
The problem is that you are only checking to see if "submit" is set.
Your if statement should read something like:
if(isset($_POST['submit']) && all_other_fields_are_valid($_POST)){...}
function all_other_fields_are_valid($fields)
{
//logic to decide what fields and values you require goes here
}
You need to check all required field. only check submit it will attempt mailing:
if (isset($_POST['submit']
, $_POST['ime']
, $_POST['prezime']
, $_POST['email']
, $_POST['poruka']))
Additionally you can validate from the client side using new HTML5 required attribute:
<input type="text" name="ime" id="ime" required />
This way you don't waste server resources for bad formed requests.
Actually since they are sent as empty variables, they will still evaluate to true in isset(), even if there is no text in the input fields when they are submitted.
if($_POST['ime'] && $_POST['prezime'] && $_POST['email'] && $_POST['poruka']) {
// do stuff here
}
As long as all of these have values and none of the values are 'false' or '0', this will evaluate to true only if somebody puts text in all of the input fields.
This will check if all required POST vars are set, if they're empty and give an error if so:
<?php
if (isset($_POST['submit'], $_POST['ime'], $_POST['prezime'], $_POST['email'], $_POST['poruka']))
{
$error = "";
if($_POST['ime'] == ""){
$error .= "ima was empty!<br />";
}
if($_POST['prezime'] == ""){
$error .= "prezime was empty!<br />";
}
if($_POST['email'] == ""){
$error .= "email was empty!<br />";
}
if($_POST['poruka'] == ""){
$error .= "poruka was empty!<br />";
}
if($error == ""){
$ime= $_POST['ime'];
$prezime= $_POST['prezime'];
$email= $_POST['email'];
$poruka= $_POST['poruka'];
$email_from = 'neki#email.com';
$email_subject = "forma sa sajta";
$email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ;
$to = "myemail#gmail.com";
mail ($to, $email_subject, $email_body);
echo "Message is sent";
} else {
echo $error;
}
} else {
echo "Message is not sent";
}
?>

PHP 5 HTML 5 contact form

I am very new to website design/programming and learned allot of html, css and a bit of php over the past few weeks. This is my first post here, Wish me luck :)
I am attempting to create a mail form from what I have learned from various websites, the form works but I have an issue with sanitizing the input, I'm not sure if I am doing it correctly as I can still "inject" code into the fields.
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
if (isset($_POST['submit'])) {
$error = '';
// Name
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
// Telephone Number
$phone= filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
// Email Address
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error = 'You have not entered a valid email address.<br/>';
}
// Message
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (empty($error)) {
$from = 'From: ' . $name . ' <' . $email . '>';
$to = 'YourEmailHere';
$subject = 'Message from Contact Form';
$content = $name . ' has sent you a message: \n' . $message . '\n\nPhone Number: ' . $phone . '\n\nIP: ' . $ip . '\nBrowser:' . $browser;
$success = '<h3>Thank you!<br /> Your message has been sent!</h3>';
//mail($to,$subject,$content,$from);
}
}
?>
<h1>Contact Form</h1>
<br/>
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/><br/>' . $error . '<br/><strong>Please try again.</strong><br/></p>';
} elseif (!empty($success)) {
echo $success;
}
?>
<form action="" method="post">
Name:
<input type="text" name="name" required placeholder="Name" value="<?php { echo $_POST['name']; } ?>"><br/>
Telephone:
<input type="text" name="phone" required placeholder="Telephone Number e.g.0123456789" value="<?php { echo $_POST['phone']; } ?>"><br/>
Email:
<input type="text" name="email" required placeholder="Email Address" value="<?php { echo $_POST['email']; } ?>"><br/>
Message:<br />
<textarea name="message" required placeholder="Message" rows="20" cols="20"><?php { echo $_POST['message']; } ?></textarea><br/>
<input type="submit" class="submit" name="submit" value="Send message">
<br/>
</form>
<!-- Below is Just for testing -->
<?php echo '<br/>Name : ' . $name . '<br/><br/>Phone : ' . $phone . '<br/><br/>Email : ' . $email . '<br/><br/>Message : ' . $message . '<br/>'; ?>
<br/>
</body>
</html>
I'll add layout/css later once I get the code working the way I would like.
any assistance will be most appreciated.
The "injection" code I am testing with is simply
"><script>alert('Broke');</script>
the sanitize works fine if I leave out the leading ">, even just using the "> alone messes up and page a little, I would like to know if there is a way to filter these just using options available in php.
Once I get input into this simple form working correctly I plan to use database functionality on the rest of the site so it is important to me that I get a good understanding of filtering for obvious reasons.
Thanks in Advance.
Aaron
Another Question, as you can see from the code I display an error if the email address is not valid according to the FILTER_VALIDATE_EMAIL, how would I go about doing this on the other fields (Name[text only], Telephone Number[10 digit telephone number] and Message[text with punctuation]) ?
I am also looking to add captcha script, a simple "random number [random calculation type +-X/] random number = answer" with the random numbers and calculation type displayed as an image, not sure where to start with this or if it would be too complicated for visitors.
You are doing some basic sanitising and validation but then proceeding to echo the raw (un-sanitised data) back to the client within the form.
<?php { echo $_POST['email']; } ?>
Change your value outputs to check for the sanitised values and output them appropriately.
<?php echo (isset($email) ? $email : ''); ?>
You are echoing the $_POST variables without sanitising them.
Wrap them in htmlspecialchars() like this:
echo htmlspecialchars($_POST['message']);

How do I make my PHP form errors show on the same page?

I have a simple contact form with some PHP validation attached to it. However, when a field if left blank and the form is thrown one of these errors, it redirects to a blank page and just echos out the error on a blank screen. How would I go about keeping these errors on the same page? The errors don't have to validate instantly, just when someone clicks send. Optimally it would just direct to the contact form page and have an added string of text about the form that tells the user that there was an error.
PHP
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
if ($name == "") {
// header("Location: contact.php");
echo "You must speciy a value for name.";
exit;
}
if ($email == "") {
// header("Location: contact.php");
echo "You must speciy a value for email.";
exit;
}
if ($subject == "") {
// header("Location: contact.php");
echo "You must speciy a value for subject.";
exit;
}
if ($message == "") {
// header("Location: contact.php");
echo "You must speciy a value for message.";
exit;
}
foreach( $_POST as $value ) {
if( stripos($value,'Content-Type:') !== FALSE ){
echo "There was a problem with the information you entered.";
exit;
}
}
if ($_POST["address"] != "") {
echo "Your submission has an error.";
exit;
}
require_once("class.phpmailer.php");
$mail = new PHPMailer();
if (!$mail-> ValidateAddress($email)){
echo "You must specify a valid email address";
exit;
}
$email_body = "";
$email_body = $email_body . "Name: " . $name . "<br>";
$email_body = $email_body . "Email: " . $email . "<br>";
$email_body = $email_body . "Subject: " . $subject . "<br>";
$email_body = $email_body . "Message: " . $message . "<br>";
$mail->setFrom($email, $name);
$mail->addAddress('email#gmail.com', 'Staff');
$mail->Subject = "Contact Form | " . $name;
$mail->msgHTML($email_body);
//send the message, check for errors
if (!$mail->send()) {
echo "There was a problem sending the email: " . $mail->ErrorInfo;
exit;
}
header("Location: contact.php?status=thanks");
exit;
}
?>
HTML
<div id="contact-form">
<div class="container">
<div class="row">
<div class="col-md-6">
<form class="form" method="post">
<p class="name">
<div id="label"><label for="name">Name</label></div>
<input type="text" name="name" id="name" placeholder="John Doe" />
</p>
<p class="email">
<div id="label"><label for="email">Email</label></div>
<input type="text" name="email" id="email" placeholder="mail#example.com" />
</p>
<p class="subject">
<div id="label"><label for="subjext">Subject</label></div>
<select name="subject" id="subject">
<option></option>
<option>Request for Consultation</option>
<option>Ordering a Service</option>
<option>Just to Say Hello</option>
<option>Other</option>
</select>
</p>
<p class="message">
<div id="label"><label for="message">Message</label></div>
<textarea name="message" id="message" placeholder="Write something to us" /></textarea>
</p>
<div id="label" class="address" style="display:none !important"><label for="address">Email</label>
<input type="text" name="address" id="address" placeholder="123 Elm Street" />
<p>If you're a human, please leave this field blank.</p>
</div>
<p class="submit">
<input type="submit" value="Send" class="btn-blue btn-submit"/>
</p>
</form>
</div>
</div>
</div>
Two basic options...
(1) Include the error message as part of the URL.
header("Location: contact.php?error=" . urlencode("You must specify a value for name."));
You can then, in contact.php add a echo $_GET["error"]; in the appropriate place.
Biggest downside here is potential for abuse. A message included in the URL can be changed by the user, or anyone to display anything. Someone malicious might change the message to confuse or abuse a user.
(2) Use sessions to store the error message.
session_start();
$_SESSION["error"] = "You must specific a value for name.";
And then on contact.php, at the top add a session_start(); and somewhere in the page add...
if ($_SESSION["error"] != "") {
echo $_SESSION["error"];
$_SESSION["error"] = "";
}
There are more ways, but this should get you started.
You can actually do this with PHP if you do not have a great knowledge of Javascript or AJAX. You have 2 options: one of them is overcomplicated, but I will give you both anyway.
Option #1:
Send the form to the same page.
Change the action of the form to send it to whatever page the form itself is on. Then, when you want to do the error messages, instead of doing
echo "insert error message here";
for the first error msg, in your case if they left name empty, you want to do
$errormsg = "insert error message here";
for every other validation, you want to do
$errormsg .= "insert error message here";
then, just echo out the
$errormsg
if it is not null.
Option #2
This option is very overdone. It has the same concept as above, but it adds support for if you want to have the form on the other page.
Make sure you have
session_start();
on the top of both the form page and the form validation php page.
now, for the first errormsg that occurs:
$_SESSION['errormsg'] = "insert error message here";
For every other error msg after that, you can do
$_SESSION['errormsg'] .= "insert error message here";
as we did before.

Categories