Learn PHP
Site Map
PHP
HTML
Authentication
Php Functions
C++ - Starting Out
Web Design Tools
Photoshop Tutorials
Windows
Phones
Droid Phones
Building Websites
ArrowTech Blog
Web Servers
Networking
Making Money
Favorite Links
About
ObamaCare
Software
Privacy Policy

Category: php

.

PHP -- How to Protect My Email Form / Contact Form Against Spam Bots

i-1 Author: D.Shaun Morgan

Versions and Skill Level
  • PHP 5
  • Reader skill level - Intermediate
Tutorial Outline:
  1. Random Name Fields to Stop Spambot
  2. Example Random Name Fields Script
  3. Example Message Script
  4. Stopping Spam Bot With CAPTCHA
  5. Example CAPTCHA Script

By far, one of the most annoying things about operating websites is spam bots. They crawl onto our websites, suck up bandwidth, and dump a load of BS (I can think of many more colorful words that are more fitting) into our databases and email inboxes on their way out. The spam usually starts as just a few wayward, sometimes unintelligible, words and links. But before long, what was once just a passing bother, grows into a menacing 1000 messages a day. At that point the problem is costing money, leaving many a distraught webmaster wondering "how do I stop spam bots from spamming my php contact form?" That is exactly the question that this web page intends to answer.

While it is impossible to cover every possible method of securing web forms against spam bots, we can cover some basics of what other web masters are using to stop spam on their websites. The topics discussed here should be more than enough to thwart the average spammer; and with a little imagination, you will be able to mix these techniques, if needs be, and come up with more complex ways of securing your php scripts against bad bots.

Using random name fields for input

One simple way to add some security to php forms is to write a script that generates a random output for the name fields in my form's HTML input. The name field will become the name of an index entry that I use to retrieve information in which my form passed to one of the super globals in php. For this discussion we will assume that the form is using the post method.

NOTE:

Even though POST is slightly more secure than GET -- with GET a malicious bot or person needs only to look at the address bar in most web browsers to view the different variables and change their value -- one only need copy the webpage source form and duplicate the form from his own PC to send the data with POST.

Back to random name fields to stop spambots. When I first put a php contact form on my website, I coded more-or-less bare-bones, meaning that I did not bother to include any of the extra code required to secure my forms. At the period when I had zero visitors, this, of course, was not an issue. As you may have guessed, however, my spam free honeymoon was short lived. So, I did exactly what you are doing now. I went googling. Alas! After some million or so hours reading, I went back home to my little corner of the Internet and contemplated about the bad bots who were plaguing my website. While giving this subject much hard thought, I had an epiphany (actually it was more akin to a brain fart), that not withstanding, it occurred to me that the spam bots who were visiting my site were probably not reading all of my page's HTML each time they came. I also reasoned that those bots probably had algorithms that brought them back in attempts to pass off the same values they had used before. After all, if it was I who was writing a spam script, that's how I would do it; making my bot more efficient. I also reasoned that the bot would probably make a note of whether or not its' attempts to spam my contact forms was successful, and try to revisit later and adjust accordingly. I understand that there are some super bots out there who can read your mind and what-not, but I was banking on my delinquent bot being more of a basic thug with very little real skill. Packing this new found knowledge, I embarked on coding a super sophisticated random number generator for my form's name fields. Furthermore, I felt obligated to share this gem of Internet wisdom with fellow webmasters.

Random Field Script to Stop Spam Bots

Example Contact Form ^?php
$author='author'.md5(rand());
$emailll='emailll'.md5(rand());
$subject='subject'.md5(rand());
$website ='website'.md5(rand());
$_SESSION['com']="author=$author&emailll=$emailll&subject=$subject&website=$website";
?*

^form class="com" name="" method="post" action="diddly/messcript.php"*
^input type="hidden" name="webpage" value="^?php echo $_GET['url'];?*"/*
Name:^br/*
^input name="^?php echo $author;?*" type="text"/*^br/*
Email:^br/*
^input name="^?php echo $emailll;?*" type="text"/*^br/*
Your Website, if any:^br/*
^input name="^?php echo $website;?*" type="text"/*^br/*
Comment:^br/*
^textarea name="comment" cols="75" rows="20"*^/textarea* ^br/*^br/*

^input name="Submit Article" type="submit"/*^br/*
^/form*


Explanation

First, I wrote a little php script and created some variables for use in my form's name-field; then I set those variables to random md5 hashed values.

Notice that I left part of the word intact (author for example) to help me keep track of my variables.

The random numbers alone would have likely yielded the same result; but I added the hash for the sake of making the numbers harder for a spam bot to guess.

Next, I added all those values to a single string, and saved that string in a session variable.

$_SESSION['com']="author=$author&emailll=$emailll&subject=$subject&website=$website";";

Notice the example form above. I echoed the variables from the "random script" to their respective name fields.

With this form in place, the bad bot cannot rely on the field names that it used on its' last visit to spam my email form.

Now let's examine what I did with this form and Script information when it got to my script " messcript.php."

Example PHP Message Script

^?php if(!empty($_SESSION['com'])){
parse_str($_SESSION['com']);
}else{
do something else
}
if(!empty($_POST["$author"])
&&!empty($_POST["$emailll"])){
$author = $_POST["$author"];
$email = $_POST["$emailll"];
$website = $_POST["$website"];
$comment = $_POST["comment"];
SAVE TO DATABASE. SEND EMAIL Et cetera
}
?*

Explanation

I check, first, that the variable "$_SESSION['com']," in which I stored a string of values ("author=$author&emailll=$emailll&subject=$subject&website=$website") is not null or empty.

If $_SESSION['com'] is set, then my script goes on to parse the info that is contain therein by calling the php function "parse_str()." (feel free to pass your variable values however you please. I like using "parse_str()."

Next, my script makes sure that the other various vars (variables) are set. Make note of the "$_POST" variables. Notice how I used as indexes the variables that I sent over using "$_SESSION". After getting that data to script, I transfer the values into local vars and proceed with database and email code (not included here for security).

I tested this method of using random name-fields to stop spam on my php contact forms. After implementing this, spam went to zero. Fearing, however, that the spam-bot's master may get wise to my efforts to thwart his evil efforts, and, in turn, sick one his smart bots on me, I decided to go one step further by installing a php captcha to stop form spam.

Just to be clear on the random field generator that I created for my form -

I will explain why I decided on this. I guessed that these bots came through and read the "name attributes" of form tags. If the name attribute says email, the bot knows that it is an email field, or a firstname field etc. Then based on what type of field it found it would have logic written into it telling it what to do if it finds something like that. I thought that maybe if the bot did not see a field name that it "knew," it may skip over it or not know what to do with it. Also - since everytime your form comes up it has a different random name for its name fields - no one can set somewhere else and keep sending stuff to my form remotely based on the variables you found before. They would HAVE to use my form page because they cannot guess what the name fields are. The idea is to confuse the bot'a logic.

Stopping Spambots With php Captcha

Captcha you know, that little image of squiggly lines that you see all over the Internet in places where you want to post something? The idea is that bots, unless they are extremely sophisticated, cannot read the letters on the captcha image. Captcha is pretty easy to implement depending on whether you are running a custom site like mrarrowhead.com or you are using software like Wordpress. This discussion only covers the former. Here at mrarrowhead.com we like to "roll-our-on" so to speak Just love that good homegrown flavor that you can't get from a box o'website. Really though, I have no problem with Wordpress and other website software; I just don't like to muck around with someone else's code. Anyway, back to captcha.

I first intended to write up my own captcha (because I like to do stuff like that), but for the sake of saving time, I googled around until I found a script that I liked. I'm not going to spend a lot of time on this captcha because I didn't write it. The person who wrote it is listed in the code's license; I suggest you check that for an in depth explanation of a the captcha script. This webpage is intended for folks who already have a pretty good feel for PHP. That said, the code should need little explanation, so I will just give you the quick and skinny. Lets go back to our original form. This time I will add some extra code for the captcha.

CAPTCHA script to stop spam bot

^?php
$author='author'.md5(rand());
$emailll='emailll'.md5(rand());
$subject='subject'.md5(rand());
$website ='website'.md5(rand());
$_SESSION['com'] ="author=$author&emailll=$emailll&subject=$subject&website=$website";
?*

^form class="com" name="" method="post" action="zxcvzxcvzxcvcx/messcript.php"*
^input type="hidden" name="webpage" value="^?php echo $_GET['url'];?*"/*
Name:^br/*
^input name="^?php echo $author;?*" type="text"*^br/*
Email:^br/*
^input name="^?php echo $emailll;?*" type="text">^br/*
Your Website, if any:^br/*
^input name="^?php echo $website;?*" type="text">^br/*
Comment:^br/*
^textarea name="comment" cols="75" rows="20"*^/textarea*
^br/*^br/*
^img src="zxcvzxcvzxcvcx/capimg.php"/*^br/*^br/*
Enter The Above Security Code:^br/*^br/*

^input id="security_code" name="security_code" type="text"/*
^input name="Submit Article" type="submit"*^br/*
^/form*

Take notice of the additional code:
  1. ^img src="zxcvzxcvzxcvcx/capimg.php"/*
  2. ^input id="security_code" name="security_code" type="text"/*

The first line of new code calls a php script that generates a random lot of numbers and outputs them as an an image.

Click to View Captcha Image Script -- capimg.php and license.

Someone asked me to be more specific about the capimg.php script and where it goes.

If you are having trouble udnerstanding how to use this script do the following

  1. Create a directory for your scripts
  2. Save this image as capimg.php
  3. Create a landing page for your form -- the one that you have in the "action=" attribute of your form tag. The I created is messscript.php
  4. Use the following code at the top of your landing page:

    if(($_SESSION['security_code'] == $_POST['security_code'])&&
    (!empty($_SESSION['security_code'])) ) {
    Code to do some stuff
    }
  5. make sure that you have session_start() at the top of your pages or it will not work.
  6. Point to the capimg.php script by placing its address in the >img src"" /> script
  7. You will also need to place this font file into your folder gunplay3.ttf
    If you wantto use a different font you can drop a different font into your folder and change the value in the capimg.php file.

Basically, the new input works with the image file to produce an image that the spam bots cannot read. You will want to place the following code on your target script, in this case " messcript.php," to deal with the captcha.



if(($_SESSION['security_code'] == $_POST['security_code'])&&
(!empty($_SESSION['security_code'])) ) {
Code to do some stuff
}

The two methods described in this discussion have, thus far, been very effective at stopping spam bots on my server. As of yet, I have received no more bot spam. Check back often. In the near future, I will be going over other php scripts that will help you keep out spam bots.

Author: D.Shaun Morgan

convert timestamp to readable date time using php Convert Unix Timestamp to Readable Date Time PHP User Function string function convert_timestamp(string $file_in

creating image watermarks Creating PHP Watermarks $my_image = imagecreatefromjpeg('photo.jpeg'); $watermark = imagecreatetruecolor(100

need to print out an array using php How toPrint PHP Arrays Things to Consider Are: Array Type- Single Array or Multidimensional Array

php      

odd number php script Testing for Odd/Even Numbers - PHP Example Banner Rotation PHP Script Odd/Even Numbers The easiest way to setup an Odd / Even test using PHP i

how to upload images and files using php Upload Images to Webserver HTML Form PHP Function # UPLOAD FILE function upload_file(){ echo '

using php cookies variables Using Cookie Variables in PHP Setting cookies in php is pretty straight forward. There is a php function: setcookie(); This function mu

how to unzip files on your free hosting account Uzipping Files on Your Web Server If you are using a free hosting account with godaddy.com and many of the other Free hosts out there, you may have found that they don't offer you a lot o

passing data from one form to another form using php Passing data from one form to another form To pass php data from a form and then catch that data into another form one way to accomplish this task is to intermi

Just In Time Compiling JIT - Just in Time Compilers JIT refers to a special software that is found in web-browsers, and scripting engines such PHP's Zend. (My understanding of ZEND is that it

Storing image locations mysql Store Image URL in Database Retrieve Image with PHP Script

how to turn variable value into variable name Variable Variables in PHP Every so often when you are writing a php file, we all run into a situation where we would like for the name of the string that is inside

what-is-php Explanation of PHP Basic Syntax --New to PHP Php is a language that is very much like writing c. The best feature of PHP versus c is that it is designed pri

how to use dreamweaver Dreamweaver - WISIWIG Dreamweaver is a tool that arguably could be called the industry standard for web design . Dreamweaver, is an Adobe product that originally b

Filezilla Filezilla Ftp Client, FTP SERVER vs Wsftp By: D.Shaun Morgan While I was writing this article, about halfway through, I realized that it would be unfair to tell my readers about

notepad plus Notepad++ Download Notepad Plus Plus Notepad plus plus is an open source, free text editor. It is

how to open create write files using php Php file functions, Opening a file in php, reading a file in php, writing a file in php In this tutorial we will look at the most commonly used file functions used in php. The

stop form spam captcha PHP -- How to Protect My Email Form / Contact Form Against Spam Bots Author: D.Shaun Morgan Versions and Skill Level PHP 5

retreive images mysql using php How to get images out of mysql database with php and use them on my webpages Author: D.Shaun Morgan PHP Version - PHP 5x

how to make money online Making Money on the Internet Sign up for this series of free money making articles Name:

store images mysql using php Storing Images in Mysql Database Tutorial Outline: Creating a Test Mysql Database Example php Database Functio

php example post array Visual example of how PHP handles the super-global array variable "$_POST" Author: D.Shaun Morgan Versions and Skill Level

php arrays Passing PHP Arrays How to pass php variable arrays between pages. Author:

how to write php functions Explanation of a Basic PHP Function What is a PHP function? In PHP a function represents a block of instructions that perform

how to write html form using php When learning PHP to build a website, one of the very first things that any newcomer, or beginner needs to learn is how to use HTML or XHTML (both will mean the same for this tutorial.) fo

register globals long arrays Security, php.ini, register_globals and register_long_arrays Author: D.Shaun Morgan Versions and Skill Level PHP Version - PHP 5x

how to install php 5 How to Install PHP 5.x.x.x on Windows This is beginner's how-to manual explaining how to quickly setup a PHP 5 installation on a Windows PC. You must have an Apache webserver installed

php passing variables Pass Variables from One Page to Another -- PHP Author: D.Shaun Morgan Tutorial Outline : Passing PHP variables with $_

.

Leave a Comment

stop_form_spam_captcha.php

Name:      | Email:      | Website:

Comment:


captcha

Enter The Above Security Code:


Author: Keith | Website URL: |
Comment:
Question what is the capimg.php file look like?? I understand the rest but not that function Thanks Keith
Author: CasTex | Website URL: http://www.claymontde.org |
Comment:
Great tutorial for anti spam. Gonna try it on my blog
Author: allaboutdatingsites | Website URL: http://allaboutdatingsites.com |
Comment:
So, I guess I must be missing some critical point about the problem your are trying to solve. Is this a BotTrap? I am guessing that the form isn't a real contact form you use for your real contacts, like this one. The use of sessions is interesting but I wonder about the need for it. Seems to me that this exercise is dependent upon the assumption that the badbot figures out that this site is not useful for propagating its package and somehow makes a note that this site is a waste of time so don't come back but I don't see any proactive data capture from your script about the badbot to use or not for blocking their return? Only slightly confused... TIA for a response regards, mcs
Author: karan | Website URL: www.mytipsguru.com |
Comment:
sir I need your help. If you can send me the scripts for creating a secure send form for my website, I will be happy. karan Re:

Dear, Karan,
    I would love to help you with this request, however, I will need to know more about what you are wanting. I have sent an email directly to you. Please send more details back to my email and I will help you out.

Sincerely, D.Shaun Morgan
Author: print daily cash | Website URL: |
Comment:
Thank you for this great script on stopping form spam!
Author: sai theja | Website URL: |
Comment:
How the captcha knows the spam and bots have came to our website?
Re: Admin
The captcha does not detect spam bots. It does make it more likely that a real person will have to make entries on your forms versus a bot.
Author: Javi | Website URL: www.noneyet.com |
Comment:
Great article This is what I did myself after reading this post to store random input names. Just in case anyone needs them to be in the same page. ?php $author= author .md5 rand session_start if empty $_SESSION { if isset $_POST[ submitted ] { echo p b This was your previous input name: b br .$_SESSION[ name ]. p p b This is your actual input name: b br $author p $namevalue = implode , $_SESSION echo p b This is what you wrote: b br .$_POST[ $namevalue ]. p $_SESSION[ name ] = $author } } ? form method= post action= pruebasrapidas03.php Write something: br input name= ?php echo $author ? type= text br input type= hidden value= true name= submitted input name= Submit Article type= submit br form ?php $_SESSION[ name ] = $author ?
Author: George | Website URL: http://www.linkpouch.com |
Comment:
I tried to implement your idea. It has a main drawback. If a user has two tabs open in his browser, he will not be able to comment in both since after opening the 2nd one, he will get new session variables that will not work anymore for the first tab. This is a general situation when you use session variables for validation.


Re: Admin


Hmm... Great point. I started using this captcha back before tabbed browsing was around, and honestly, I did not test a lot with several opened pages. I encourage anyone who wants to use it, to play around with it. Update it some , document the updates, and send it back to me, I will put your update on the site and plug you on your site.
Author: George | Website URL: www.linkpouch.com |
Comment:
To be more specific: I was referring to the Using random name fields for input . That what I implemented. I tried to do that for the comments pages in the website I am developing. But I realized this session problem. My solution for a possible spam problem is the following: First of all, only registered users can comment. In case i realize any automated spam msgs, I will update the code so after 10 msgs the user will have to login again. It might be annoying for the user, but 10 msgs gives him enough time. This is my strategy so far.

admin for

I tried to implement your idea. It has a main drawback. If a user has two tabs open in his browser, he will not be able to comment in both since after opening the 2nd one, he will get new session variables that will not work anymore for the first tab. This is a general situation when you use session variables for validation.


Re: Admin


Hmm... Great point. I started using this captcha back before tabbed browsing was around, and honestly, I did not test a lot with several opened pages. I encourage anyone who wants to use it, to play around with it. Update it some , document the updates, and send it back to me, I will put your update on the site and plug you on your site.


Re: Admin


Sounds like a plan. The random names is not something I tried in a setting such as yours. Everything on this site with the exception of the captcha is 100% my own code. The older stuff is obviously not as good as the newer stuff,and I have learned a lot along the way. There are certainly a lot of other ways to accomplish the task of getting rid of spammers. I found it interesting when I first wrote it that the spam bots were not able to get past the random field names. It only adds a little protection and I can see how using session variables could be a problem. It may work better with cookies. I might pick it back up and update it some. Thanks for the reply.
Author: cheap rolex | Website URL: http://www.xiliwatches.com/luxury-replica-rolex-watches-cb354.html |
Comment:
Fantastic info. This is a terrific blog site, I wonder to know how you designed it? If it is possible, e-mail me Thx a lot
Author: u boat montre | Website URL: http://www.demontres.fr/replique-u-boat-cb204.html |
Comment:
Your article is very good, very good with words, the sentence is smooth, rich in content.
Author: Darla | Website URL: http://www.iconbet88.net/ |
Comment:
Informative article, just what I needed.
Author: Carrol | Website URL: https://www.Facebook.com/seofrontpage |
Comment:
Do you mind if I quote a couple of your articles as
long as I provide credit and sources back to your webpage?
My blog site is in the very same area of interest as yours and my users would definitely benefit from some of
the information you provide here. Please let me know if this okay with you.
Thanks
Re: Admin
Yes it is ok to quote as long as you link back and give credit.
Author: Martha | Website URL: http://flatfeetandshoes.wordpress.com/ |
Comment:
I gotta say, I am more amazed by the “generic commenter” than I am by the blatant spammer. Why? at least the obvious spammer is completely open and honest with their intentions I know who they are. The generic spammer is a liar and a charlatan You can probably see that I have strong feelings towards these type of “individuals”
Author: Cecile | Website URL: |
Comment:
Good info. Lucky me I recently found your blog by chance stumbleupon .
I have book marked it for later
Author: tony | Website URL: www.tonyreaode.com |
Comment:
i am testing your form : i want to copy this , if u dont mind can i pleeeease copy. thanks
Author: Veta | Website URL: http://cursosinemweb03.wordpress.com/2013/08/28/cursos-gratuitos-de-tecnicas-de-seleccion/ |
Comment:
Excellent post. Keep writing such kind of information on your blog.
Im really impressed by your site.
Hello there, You have performed a fantastic job.
I will definitely digg it and personally recommend to my friends.
I am confident they will be benefited from this website.
Re: Admin
Thank you from http://MrArrowhead.com - please link back to us.