Honesty Rocks! truth rules.

Preventing Spam When Using Php's Mail Function

HOME      >>       Programming


First of all, if this is not the correct place for this topic please an Admin move it accordingly.

Recently i read at the PHPBuilder.com website this excelent article Preventing spam when using PHP's mail function that explains in a very easy way how to avoid spammers send their spam from your own server.

Generally speaking, almost all websites includes some kind of contact form which is used to send emails with the php mail() function, this contact form can be used for a lot of purposes like for example to send comments or sugestions, to report problems on your website, to register users, etc. and can be used and abused by spammers to send out their spam without your knowledge.

This article is very easy to understand and to implement, includes functions for checking valid emails and to prevent scripts to be exploited.

You can use it as a good starter point to prevent this issue to happen and I hope it helps somebody.

Best regards,


if this is not the correct place for this topic please an Admin move it accordingly.

No problem, I accept this post here.However, on the topic subject, I would like to understand something. Do you mean that you could send mails without this kind of contact form, and having your mail being received correctly ? :)


No problem, I accept this post here.

However, on the topic subject, I would like to understand something. Do you mean that you could send mails without this kind of contact form, and having your mail being received correctly ? :)

Thanks yordan to move it, and i don't completely understand your question but just in case, my answer is yes.


For example, you have a page -form.php- with a contact form and other data in it, that when it is submitted goes to another page -mail.php- which receives all of the submitted data and then sends an email with the mail() php function as usual. For the sake of the example, this is the same code from the article without any kind of validation. The code of the mail.php is:


$to = "bob@domain_example.com";
$subject = "Email from website";
$message = $_REQUEST["body"];
$email = $_REQUEST["email"];
$headers = "From: $email";
mail($to, $subject, $message, $headers);echo "Thanks for submitting.";

If you don't perform any kind of validation in any of these pages, then it is very easy for a spammer to send emails with your page in this case with your mail.php page.


How??? It is very simple, first you only need to view the source code of your form to get the variable names and to where it will be redirected. The first ones are all the elements of your form and the second one is the value of the ACTION property of the form.


So, it is very easy to send a request like this:


to abuse it and send my spam.


On the other hand, if you do some kind of validation, your pages will be a lot more secure and will help you to prevent this situation. This is my code with some validation:


<?phpfunction contains_newlines($str_to_test) { if(preg_match("/(%0A|%0D|\\n+|\\r+)/i", $str_to_test) != 0) { echo "newline found in $str_to_test. Suspected injection attempt - mail not being sent.<br />"; echo "here you must use the exit or die php functions to finish the script.<br /><br />"; // exit; }} $to = "webmaster@gigasoft.astahost.com";$subject = "Email from website";$message = $_REQUEST["body"];$email = $_REQUEST["email"];$headers = "From: $email";if($_SERVER['REQUEST_METHOD'] != "POST"){ echo "Unauthorized attempt to access page.<br />"; echo "here you must use the exit or die php functions to finish the script.<br /><br />"; //exit;}contains_newlines($email);// mail($to, $subject, $message, $headers);echo "to = $to<br / >subject = $subject<br / >body = " . $_REQUEST['body'] . "<br / >message = $message<br / >email = " . $_REQUEST['email'] . "<br />headers = $headers<br /><br />";echo "mail ($to, $subject, $message, $headers)<br /><br />";echo "Thanks for submitting.";exit;?>

Best regards,


OK, now I see, thanks a lot Tavox.


Well, by doing a little validation and even programming in a "good" way, these kind of problems won't happen, of course, I know one thing: when you do something for yourself or you're still learning and quite well, you try to do different things, but when you're working and doing for somebody else, not always you have time to do it in a very "perfect" way, the main thing for most clients are that it would work, usually they don't care about the code, or what language it is or how it's possible and for that reason, I really can say that there are lots of "bad" scripts/programs written out there, to get money and to make it work..I saw some really bad scripts, especially written in php, the main things as I said that they would work, and they do! When things like frameworks appeared, it's a little safer for people who write their applications in Zend framework or any other good framework, it is more secure, it saves time too and you have a better application, the bad thing about it in my opinion, that there are thousands of copies in some library directory of for example zend frameworks :) they are there, even though only 4% of them are used..To conclude, for example I remember I always wanted to write "the best way" in my sites or cms and I even do Today, but when I started doing something not for myself I understood that the main thing is to make it work, I still prefer to make a good application though, but time is money, but with experience I think still most of them are quite good, even written fast :) I remember I thought to write for others, you need to comment and write it that other people who might try to edit them or something, that it would be as easier as possible for them, but in most cases, if you wrote the application, bigger chances are that they or he/she will ask support from you again and not from any other guy for support, so you can write it your style or by how you like it ;)


Yordan, no problem and i'm glad that now you see it better.


Quatrux, you are right, TIME IS MONEY, and when you work for someone else it is a thing that counts a lot, other thing that also counts a lot is that IT MUST WORK. Related to good and bad scripts, always both of them will exists and we can't do anything about them, but for ours, yes we can.


I know that nothing is perfect and never will be, but i'm the kind of person that always try to do my best effort in anything i do, and when it is about programming a bit more, because i know that i can improve my code. I think that it is better to first try in your personal projects and then with the experience that you gain with it apply to your professional work which pay the bills.


BTW, my code posted here is to much simple and i only make it for testing purposes, also, i know that it is not correctly coded, it is not complete and finally I must complete and improve it shortly.


So, please be honest with me and tell me what do you think about it???


Best regards,


Is there any way to block incoming spam mails using PHP script

Preventing Spam When Using Php's Mail Function


The script you provided is really good to block out going spam mails from the server on which your sript is running,, but how to block the in coming spams mails on your server. Is there any useful script for that also...



Regards muryam


-question by Muryam


Few weeks before I have seem an article that state the use of regular expression is not necessarily safe to vaildate an email address. (sorry I forgot the web address)So, did you think add some hidden fields with values that generated dynamatically would help a bit ?Also, is this fields really help for this checks.---Magiccode9


Hidden fields are not useful because an attacker could still alter/inject data into the data sent through hidden fields. The best way to do this is all within the server.


If hidden fields are not safety and should done all checking with server-side.
What's the best way to check it ?
Is this kind of checking enough ? like,

<?php$username = isset($_POST['username']) ? $_POST['username'] : null;// do some other characters replacement// finally, we are slashes single quotes .. etc.if (get_magic_quotes_gpc()){ $username = addslashes($username);}?>




Thank you, i liked your lesson. I'll wait for another.


I don't completely agree with FirefoxRocks, because despite the fact that hidden fields can be useful at the same time can be exploited by an attacker. If used, it is best to use them in forms with the POST method and do the validation on the server side.


@magiccode9: your code is fine, but i recommend to do a quick search on the forums because i know that there are a lot of topics related to this subject. For example these are some topics that can be helpful:

PHP Tutorial: Form Verification and Simple Validation.


Magic Quotes And $_FILES.

@Bermuntas: you are welcome.


Best regards,


Spam EmailPreventing Spam When Using Php's Mail Function

When I'm trying to send an HTML email using PHP Mail function, the mail will send to a spam folder. I want , the mail should send to an inbox. Can anyone know how to avoid this problem?



I use a simple advice from php tutorial:
All what you need is an input field and a PHP code to check the
entered code. Here is an example code for the HTML form:

Access code: <input /><br />

Please enter <b>MYCODE</b> above.

Then you can simply the check if the entered code matches, with a PHP
help. Please, compare the code in lower-case to avoid issues with a
typing in CaSe SeNSiTiVe code:

If (strtolower($_POST[âcodeâ]) != 'mycode') {die('Wrong access

The form will be submitted only after the time, when the person
enters the correct access code.
Maybe it is too easy, but it is effective


Hi!Bocarius, the solution that you have provided is simple and effective against bots. Bots are really the most annoying of things you have to prevent abuse from, but you might occasionally who hit the refresh button on the web browser when they don't see anything happening, so that's probably another source of problems.Perhaps you could build up a database of questions, such as "What is the color of the sky" and get answers to those questions. A different question can be provided to the user each time.For a new site that I'm coding, I would probably just do what you've suggested - type in a single word and check for it in script - to get my site up and running, before I make enhancements to the functionality.