I'm having an issue where my PHP mail code runs every night at like 11:30pm. I'm sure no one is clicking the form submission button. The email contents are empty.
In my PHP mail code, I add the contents to a database just in case the email does not go through, then send the email as well.
Thanks
Form:
<form action="background/mail.php" method="POST">
<div class="row">
<div class="six columns">
<label>Your email</label>
<input class="u-full-width" type="email" placeholder="example#validmail.com" name="email">
</div>
<div class="six columns">
<label>Reason for contacting</label>
<select class="u-full-width" name="reason">
<option>Inquiry</option>
<option>Order</option>
<option>Other</option>
</select>
</div>
</div>
<div class="row">
<div class="u-full-width">
<label>Message</label>
<textarea class="u-full-width" placeholder="Enter message here" name="message"></textarea>
<input class="button-primary" type="submit" value="Submit">
</div>
</div>
</form>
mail.php:
<?php
$to = "support#website.ca";
$reason = "CUSTOMER MAIL: " . $_POST['reason'];
$email = $_post['email'];
$msg = $_POST['message'] . "\nemail: " . $email;
$header = "MIME-Version: 1.0\r\n";
$header.= "Content-type: text/html\r\n";
$header.= "From: " . $email . "\r\n";
$header.= "Reply-to: support#website.ca\r\n" . "X-Mailer: PHP/" . phpversion();
require("login.php");
$sql = "INSERT INTO emails (email, message, reason) VALUES ('$email','$msg','$reason')";
if($conn->query($sql) === TRUE){
mail($to,$reason,$msg, $header);
echo "Added to database, mail sent.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Most likely someone is making POST requests directly to your mail script to send out emails. There are some non-fool-proof ways to stop this:
Add some checking for the contents of the POST request. e.g. no empty body, valid email address, other logical checking. (you should be doing this anyway).
Add an additional hidden field to your form that is empty. Confirm that it is empty in mail.php in order to proceed. The idea: crawlers try to fill all form fields, but a user won't fill in a hidden form field
Add a hidden field and fill it with some value using JS and validate in mail.php. Crawlers cant use Javascript so the field will be empty (gotcha: will not work for users that disable JS).
Any of these can be circumvented, but they are trivial to implement and make things slightly more difficult for the crawler.
For true security there are more complex solutions. Maybe someone can outline those in an answer.
As I stated in comments in having fallen victim to a bot (or many bots); here is what I use to block out certain IP addresses and used as an include in every file.
You should also check for empty() fields and use an isset() against a submit button.
The following doesn't need the last 4th set, but you can always add to it, as it checks for anything following the 3rd set.
You can even narrow it down to using only 2 sets.
$ip = $_SERVER['REMOTE_ADDR'];
$nums = explode(".", $ip);
$if = "{$nums[0]}.{$nums[1]}.{$nums[2]}";
$blacklist = array(
"184.154.139",
"123.4.111",
"234.5.678"
);
if (in_array($if, $blacklist)) {
// echo "Rejected";
header("Location: http://www.example.com/");
exit;
}
else {
// Run your other code to do the variable check, mail processing etc.
}
I.e.:
Name your submit button:
<input name="submit" class="button-primary" type="submit" value="Submit">
Then check if it's set and that none of the POST arrays are (not) empty:
if(isset($_POST['submit'])){
if(!empty($_POST['reason']) && !empty($_POST['email'])){
$reason = $_POST['reason'];
$email = $_POST['email'];
// Run your executables in here
}
}
Another effective method is to use a checkbox and to validate if it was checked or not.
Also as stated, your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
Plus, that syntax error about $_post that I stated in comments, needs to be in uppercase $_POST as it's a superglobal.
http://php.net/manual/en/language.variables.superglobals.php
Related
I'm trying to create a PHP form that allows users to insert their email address and it automatically sends me an email with their email address. something like a subscription.
what I have so far is this:
<form action="" method="post">
<input type="email" name="email" placeholder="Enter your email address" /><br>
</form>
I found this PHP sample that I believe answers my problem, but I have no idea how to call it from my HTML.
<?php
if(isset($_POST['email'])){
$email = $_POST['email'];
$to = 'myemail#something.com';
$subject = 'new subscriber';
$body = '<html>
<body>
<p>Email:<br>'.$email.'</p>
</body>
</html>';
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset-utf-8";
$send = mail($to, $subject, $body, $headers);
if($send){
echo '<br>';
echo 'thanks';
}else{
echo 'error';
}
}
?>
There's insufficient code for me to be able to answer completely, but the one thing that comes immediately to my mind is not leaving action="" empty. Try $_SERVER['PHP_SELF'] variable, it should print the path to the file that is currently running so you'll be presented with the same page, but with data in $_POST you'll send. You can try it like this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="email" name="email" placeholder="Enter your email address" /><br>
</form>
If you wish to send data to the same file like this, please make sure your PHP code is in the same file as the HTML structure of your form. It may make things easier if you put your PHP code first, so you can exit; from the file (not displaying the form anymore) telling the user that the message has been sent or that the error has occured.
I am trying to get a simple two-field form to submit to an email address and then echo a "thanks for registering your interest" below the form (or instead of the form).
FYI, this is on a WordPress template file.
Here is the code, including the form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
method="POST" autocomplete="on" id="register-form">
<input type="text" name="name" placeholder="Name"/>
<input type="email" name="email" placeholder="Email address"/>
<button type="submit" name="submit" class="button">Send
<img src="<?= get_image('icon-arrow-right-tiny.svg'); ?>"/></button>
</form>
<?php
if (isset($_POST['submit'])) {
// validate the email address first
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
// process the form only if the email is valid
if ($email) {
$to = 'info#example.com'; // where you want to send the mail
$from = 'info#mydomain.com';
$subject = 'Website Submission';
$message = 'Name: ' . $_POST['name'] . "\r\n\r\n";
$message .= 'Email Address: ' . $_POST['email'] . "\r\n\r\n";
$headers = "From: $from\r\nReply-to: $email";
$sent = mail($to, $subject, $message, $headers);
} ?>
<p style='color: #fff; font-size: 14px;'>Thank you for registering your interest.</p>
<?php
}
?>
At the present time, the form does get sent, and the page does echo "Thank you for registering your interest" underneath the form, however it does not seem to be returning us to the correct page when you click the submit button.
Any ideas?
Thank you for all of your contributions. I have worked out the problem, and will share here for anybody else who comes here to find the answer.
WordPress has something important reserved for the "name" parameter, and thus you can't use it in PHP-based forms. Changing the parameter name from "name" to something else resolved the issue.
Additionally, WordPress also has the following names reserved and you cannot use them in forms - "day" "month" and "year".
I have check your code i think you have use color code #fff i.e. for the message.
Please try to make black or any other color rest of code are working.
:)
Thank you for registering your interest.
You have to put a php code below your Thank you message.
header("location:$_SERVER["PHP_SELF"]);exit;
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"
I have searched for this answer on Google and Youtube but have not found an answer.
I have created a very simple contact form on my website.
(http://www.torontoimc.com/contact)
I have attached a seperate PHP file to process the contact form elements.
When someone sends me an inquiry through the form on my site, I'm receiving all of the information except the person's email address input section info.
It's very important that I receive that email address otherwise I won't be able to reply to whom ever sent it to me.
I have tried setting the form to be sent to my gmail and outlook email but it just sends it as:
It just shows that the sender's email address as some random name "#hemi.websitewelcome.com"
I'm not sure if this is a server side issue or an issue with PHP file.
I have attached the code for both my Contact form and PHP file.
Here is the contact form code:
<form action="formprocess.php" method="post" name="contact">
<fieldset>
<label>First Name</label>
<input name="first_name" type="text"/>
<label>Last Name</label>
<input name="last_name" type="text"/>
<label>Email</label>
<input name="email_add" type="text"/>
<label>Please write your inquiry below.</label>
<textarea name="message" rows="15" cols="40">
</textarea>
<input type="submit" name="submit" id="submit" value="Submit"/>
<input type="reset" name="reset" id="reset" value="Reset"/>
</fieldset>
</form>
Here is the php code:
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_add = $_POST['email_add'];
$message = $_POST['message'];
$to = "torontoimc#gmail.com";
$subject = "Inquiry for TorontoIMC";
mail ($to, $subject, $message, "From: " . $first_name . $last_name . $email_add);
header('Location: thanks.html');
exit();
?>
I apologize if this is a repeat question but I'm a newbie to php and have not really been able to find an answer, if someone can please help me out, I would really appreciate it.
Thanks,
Latish Vohra
Try this:
$headers = "From: $first_name $last_name <$email_add>\r\n";
mail ($to, $subject, $message, $headers );
I added "\r\n" to From
I understand what you are trying to do on the FROM line, but you should use the "real" FROM sender. Many servers will not allow you to use a FROM line from a domain that is not the host's (think about it, the truth is you are lying, the person that filled the form did not actually send that email).
Secondly, follow user4035's way of styling the email in the FROM, if you are going to use a name last name <email>, it may not only be the way to do it for normal practice, also in the way that you wrote it, joining the fields without spaces, you might end up with a FROM line such as this FrançoisMARTIN MELLIERfmartinm#gmail.comwhich may contain illegal characters and/or spaces that may cause some servers to choke on or discard. Instead 'FROM: '. $first_name . ' '. $last_name. ' <'. $email_add. '>' will produce FROM: François Martin Mellier <fmartinm#gmail.com>. But again, you should use a real account from the same domain you are sending (maybe something like 'FROM: New enquiry <info#torontoimc.com>' ?). As it's been pointed out, include the email_add field in the body of the message or the subject line in order to receive it; those are the proper places.
Using the -f parameter like mti2935 pointed out is always a good idea, but only if that email coount belongs to the same domain as the server's.
As a side note, try to take errors into account, a minimum:
if (mail ($to, $subject, $message, $headers )) {
header('Location: thanks.html');
} else {
header('Location: error.html');
}
might go a long way.