Limit contact form emails per second/minute - php

I recently made a portfolio website and put it online on 000webhost.com. Today when I logged in, the account was suspended because someone sent more then 70 emails in a minute via my contact form - something that the webhosting does not allow.
I am looking for some way to stop this from hapening again. I used both php and javascript/jquery for form validation.
This is my curent php validation code.
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$email = $_POST["email"];
$message = $_POST["message"];
$to = "fox.team001#gmail.com";
$subject = $firstName . " " . $lastName;
$headers = "From: " .$firstName . " " . $lastName . "\r\nReply-To:" . $email;
if(validateEmail($email)){
#mail($to , $subject , $message , $headers);
}
validate($firstName , $lastName , $email , $message);
function validate ($firstName , $lastName , $email , $message){
if(!empty($firstName) && !empty($lastName) && !empty($email) && !empty($message)){
if(validateEmail($email)){
header("refresh:5; url=http://www.foxteam.net");
}else{
header("refresh:0; url=http://www.foxteam.net/contact.php");
}
}else{
header("refresh:0; url=http://www.foxteam.net/contact.php");
}
}
function validateEmail($email) {
$pattern = "^[A-Za-z0-9_\-\.]+\#[A-Za-z0-9_\-]+\.[A-Za-z0-9]+$";
if(preg_match("/{$pattern}/", $email)) {
return true;
}else{
return false;
}
}
Can anyone tell me how can I stop spammers to send spam emails?

It's very hard to stop spam coming through a contact form completely, however there are a number of methods you can use to reduce it, some of which include:
Use a honeypot - the idea behind this is to have a hidden field on your form with a generic name (e.g. answer), if this field has anything in it, then don't bother sending the email (but still tell the user that the email has been sent) - it is obviously spam as there is no other way the field could have been filled out.
IP limiting - store the user's IP address somewhere and limit the number of emails per minute/hour that each IP address can send.
Word filtering - have a list of words, if any are found then don't send the email (usualy words like viagra, penis, etc).
CAPTCHA, to me, this is a last resort. If you do use one, implement recaptcha, it is by far the best one around. But as I say, use this as a last resort, there are plenty of other methods you can use without annoying the users of your website.

You can use CAPTCHA to block robot spammers

put your if() condition into for loop which contains range 70 and then send email only. if it will over by 70 then put it over else part with some suitable message
Thanks

Related

Safely Sending Email from PHP

I've got a page on my website where users can send me a message by giving their email, name, and a message. On the front end (JS) I do some basic verification, make sure the email is formatted like an email, make sure the other boxes aren't blank, and then I send it to PHP by GET.
Now I'm aware people can do some pretty sneaky stuff by injecting malicious code into PHP. What precautions should I be taking? When I was working with MySQL, I would escape it using the mysqli escape function. What should I be doing here?
Here's my script right now:
<?php
if(!isset($_GET["message"]) || !isset($_GET["name"]) || !isset($_GET["email"])){
echo "Check all the fields are correctly filled in and try again!";
die();
}
$email = $_GET["email"];
$message = $_GET["message"];
$name = $_GET["name"];
if($email == ""|| $message == "" || $name == ""){
echo "Check all the fields are correctly filled in and try again!";
die();
}
$message = wordwrap($message, 70);
mail("email#email.com","A Message From " . $name,$message,"From: $email\n");
echo "success";
?>
A very basic way is that you can declare a variable (for example $pattern)and store regular expressions (like patterns used commonly in attacks) in it, then use preg_match($pattern, $valueFromYourForm) method to see if any of the passed values matches any of those expressions and then you can stop the execution.

php email sender code dose not work properly [duplicate]

This question already has answers here:
Does page reload ever cause post?
(3 answers)
Closed 8 years ago.
can you please tell anybody what is the error this my code. this code working properly but first time i click the send button after send message to my email. but second time i don't need to click the send button only i do refresh my page then message send automatically to my email. what's the problem?
if(isset($_POST['send'])) {
$name = $_POST['fname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$interested = $_POST['interested'];
$message = $_POST['message'];
if(!empty($name) && !empty($email) && !empty($message) )
{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Regoora Message Center";
$message1 = "Customer Name :".$name."
Customer Email :".$email."
Customer Phone :".$phone."
Customer interested :".$interested ."
Customer message :".$message." ";
mail("email#example.com",$subject,$message1);
$mess = "Successfully sent your inquiry";
}
else{
$mess = 'We are sorry, but there appears to be a problem with the form you submitted.';
}}
If your code worked properly the first time, it is because it works fine. The second time you just refreshed the page and it sent another email because 'Refresh' will always repeat your last action. If you last action was 'Send Email', refreshing the page will try to resend the email.
What you could do to avoid that is, after sending, click on the address bar (http://localhost/xxxx) and press enter. It will reset the page.

Very simple subscribe form for under construction page

I'm setting up a Magento website and before it goes live I want to set up a under construction page.
I'd like to have people who are interested to subscribe and we'll send them out a email when the shop goes live.
I tried out bunch of these bigger PHP mailing/newsletter systems, but they were way to complicated and time consuming to get into because I need to work on other things.
So I'd like to know is there a easy way to do it myself or is there a script just for this task I haven't found yet? I also searched through few tutorial sites for what I was looking for, but I couldn't find anything useful. I really just need the bare minimum for this.
Thank you in advance, hopefully this question fits to this site.
use this in your page:
<!-- Subscription Form -->
<form action="form/form.php" method="post">
<input name="email" class="email" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn_email">Send</button>
</form>
<!-- End Subscription Form -->
and this for form.php:
<?php
$to = "office#site.com";
$from = "no-reply#site.com";
$headers = "From: " . $from . "\r\n";
$subject = "New subscription";
$body = "New user subscription: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo 'Your e-mail (' . $_POST['email'] . ') has been added to our mailing list!';
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
the above script will only send you an email with the new subscription, but you can extend it to do database insertion, subscriber confirmation, etc. And also validate the data in the field where the subscriber enter the email.
Make a simple form that lets users enter a name and email address. Have the email addresses go straight into a database or some other form of storage (could be as simple as a text file).
Then, when ready, write a simple script that will send out an email to all the users in the database.

How to allow only one email address and check for the # sign to validate the email address?

I was wondering how do I allow only one email address? Also how can I only check for the # sign in the email address to validate the email?
Here is my PHP code.
if (isset($_GET['email']) && strlen($_GET['email']) <= 255) {
$email = mysqli_real_escape_string($mysqli, strip_tags($_GET['email']));
} else if($_GET['email'] && strlen($_GET['email']) >= 256) {
echo '<p>Your email cannot exceed 255 characters!</p>';
}
Don't.
Use a completely RFC-compliant validator instead, followed up with an actual mail to the address. Truly, sending a mail to the address is the only real way to make sure it's a legitimate email address.
PHP has filter_var which can be used like this:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if (strpos($email, "#") === true) {
// VALID
}
}
This is a simple way to check if common address are valid (and will not allow obvious fakes) however, this doesn't make sure your email address is valid according to the RFC 822, RFC 2822, or RFC 3696.
I would also like to point this out. That will validate an email address according to the proper RFCs.
If this is a form, you can use input type="email" in your form. It is part of HTML5, so it isn't implemented in all browsers yet.
This won't serve the full purpose, but it will prevent a single page load for obvious mistakes (forgetting # or .com) to help a little. Browsers which implement it prevent you from submitting the form if it's invalid; also, Apple devices will utilize a special keyboard for that entry with "#" and ".com" present.
(Just an extra piece of info, since I don't know your whole situation.)
how do I allow only one email address?
Run SELECT query to see if there is such an email already.
how can I only check for the # sign in the email
strpos would be enough.
Though it would be a good idea to confirm email address by sending a letter to that address, you know.
Also you have a few things to correct in your code.
your else if statement is not necessary, there should be just else
and mysqli_real_escape_string shouldn't be in the validation section. It is database related function, not validation one.
And if it's registration form, it should use POST method
so, smth like this
$err = array();
if (empty($_POST['email']) $err['email'] = "email cannot be empty";
if (strlen($_POST['email']) >= 256) $err['email'] = "email is too long";
if (!strpos("#",$_POST['email'])) $err['email'] = "malformed email";
$query = "SELECT 1 FROM members WHERE email ='".
mysqli_real_escape_string($mysqli, $_POST['email'])."'";
$res = mysqli_query($mysqli, $query) or trigger_error(mysqli_error($mysqli).$query);
if (mysqli_num_rows($res)) $err['email']="email already present";
//other validations as well
if (!$err) {
//escape all the data.
//run your insert query.
header("Location: ".$_SERVER['REQUEST_URI']);
exit;
} else {
foreach($_POST as $key => $value) {
$_FORM[$key]=htmlspecialchars($value,ENT_QUOTES);
}
include 'form.php';
}
try using regex expression for it... you can find patterns in google
on eg:
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
echo "<center>Invalid email</center>";
}else{
echo "<center>Valid Email</center>";}
}
Edited for preg_match:
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
echo "<center>Invalid email</center>";
}else{
echo "<center>Valid Email</center>";
}

Sending Email to Multiple Recipients from MySql Recordset

I want to send an email to multiple recipients using PHP mail() function. The email message is simply a reminder that a membership is due to expire so email addresses will come from MySql database query. There would anywhere from 2-10 at any given time. I found the following code but it generate errors. The problem is not with my query as it generates an accurate recordset. This is the code I have: Hopefully someone can help. By the way, I am very much a novice so need easy straight forward explanation. Thanks in advance:
<?php
$recipients = ("SELECT email FROM tblMembers WHERE search criteria=criteria");
$email_list = $db->query($recipients);
foreach($email_list as $row) {
$to = $row['email'];
$subject = "Membership Renewal";
$headers = "From: Membership Coordinator <membership#myaddress.net>\r\n";
$message = "THIS IS AN AUTOMATED EMAIL. PLEASE DO NOT REPLY""\n""etc, etc, etc";
if ( mail($to,$subject,$headers,$message) ) {
echo "Email was sent successfully";
} else {
echo "Email delivery has failed!";
}
}
?>
As far as I know, then $headers comes after $message, so you should just change the order in mail() and be more aware in future.
Change
$message = "THIS IS AN AUTOMATED EMAIL. PLEASE DO NOT REPLY""\n""etc, etc, etc";
to
$message = "THIS IS AN AUTOMATED EMAIL. PLEASE DO NOT REPLY\netc, etc, etc";
There is the syntax error, because " will end the string. You would need a . to concatenate the next string.
But you could also leave the two " out at this point, becase in a double quoted string, PHP will replace \n by a newline character.

Categories