Google Custom Search

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

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 in-boxes 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

Contact Form


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.

  • $author='author'.md5(rand());
  • $emailll='emailll'.md5(rand());
  • $subject='subject'.md5(rand());
  • $website ='website'.md5(rand());

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.


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


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 or you are using software like Wordpress. This discussion only covers the former. Here at 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

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.

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 session_start() is at the top of the 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

How To Make Browser Go Back To Last Page With Using Php

How To Make Browser Go Back To Last Page With Php8/12/2014After submitting an HTML form or clicking a link encoded with variables and information, it is often desirable to the programmer that the user's browser be automatically redirected - to go back to the previous page. The simplest way I've found to accomplish this is by using a php built-in function called - header() and a PHP built-in variable called $_SERVER['HTTP_REFERER']

Binary Search User Functions

Binary Search User FunctionThe code in the example is for finding a given value in a sorted array.If the value is not found the function will return the position of the location where it the value should be.

Php Conditional Statments If Else Switch

Conditional Statements If Else & Switch CaseIf ElseIf else is the bread an butter of programming - so-to-speak. if-else and Case Switch are known as conditional operators; they create conditions or criteria that a block of code must meet in order to accomplish a certain task. Conditions make up the logic of a script.When writing scripts there is usually a need to compare something or make a decision, for e

Textarea Code Overflow

Textarea Code Overflows and Runs Out Onto PageMy Decision to Use Textarea TagWhile working on a script for to edit content, I ran into few problems. First - because mrarrowhead is a website about building websites using php, I have had to battle with the best way to display the example code on my webpages.I tried using the HTML special chars & lt; and & gt; respectively but I found it much too time consuming and tedious trying to convert the HTML code ba

Convert Timestamp To Readable Date Time Using Php

Convert Unix Timestamp to Readable Date Time PHPUser Functionstring function convert_timestamp(string $file_in, int $column,string $dateformatReturnsReturns a string representation of the file with one column convertedstring $file_inPath To the Fileint $co

Creating Image Watermarks

Creating PHP Watermarks$my_image = imagecreatefromjpeg('photo.jpeg');$watermark = imagecreatetruecolor(100, 70);imagefilledrectangle($watermark, 0,0, 99, 99, 0x0000FF);imagefilledrectangle($watermark, 9,9, 90,60, 0xFFFFFF);$my_image = imagecreatefromjpeg('photo.jpeg');imagestring($watermark, 5, 20, 20, 'libGD', 0x0000FF);imagestring($watermark, 3, 20, 40, 'watermark', 0x0000FF);$marginRigh

Need To Print Out An Array Using Php

How toPrint PHP ArraysThings to Consider AreArray Type- Single Array or Multidimensional Array?Class-Object Array?Raw Dump of Array Keys and Values?Array Data Precision Extraction Methods?Formatted Array Data - HTML tags - Str

Odd Number Php Script

Testing for Odd/Even Numbers - PHPExample - Banner Rotation PHP Script Odd/Even NumbersSimple Php Tutorial Creating Odd / Even Testing% modulus operator.$_SESSION['x'] % 2;In this example I will demonstrate a php script that I use to rotate two Ad banners.This results in a script that changes up the banner every time the user clicks

Using Php Cookies Variables

Using Cookie Variables in PHPSetting cookies in php is pretty straight forward. There is a php functionsetcookie();This function must be called before any anything else on the page or it will fail. There are two options to address this.Use ob_start to Buffer contentYou can either make sure that setcookie() is the first thing you call in your script - which is often just not a possibility.

How To Unzip Files On Your Free Hosting Account

Uzipping Files on Your Web ServerIf you are using a free hosting account with and many of the other Free hosts out there, you may have found that they don't offer you a lot of features. One feature that I could not find on free hosting accounts was a utility that would unzip my files after I uploaded them to my server. I had a dating site software that I was trying to install after I uploaded the zip files to my hosting server.Thus, I wrote a PHP

Passing Data From One Form To Another Form Using Php

Passing data from one form to another formTo pass php data from a form and then catch that data into another form one way to accomplish this task is to intermingle your php code into your HTML to dynamically capture variable values. This particular method is useful in a scenario where the user updates something via a post (it could be a text file or database) and then the user is returned to the page where the form is located to find various fields popula

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 produces byte-code and functions similar to other JIT compilers). For this discussion, without trying to be overly technical on what a JIT is or isn't -- JIT will simply mean software that turns scripts into executable code for whatever machine it is running on. The concepts of JIT and it's various

Storing Image Locations Mysql

Store Image URL in DatabaseRetrieve Image with PHP Script Saving URL Text in Database Saving image filesystem paths, of an image file in the database is easier than saving the whole image. Storing whole images requires converting the image files into bit-streams then saved into the database as binary and then changing them back into th

How To Turn Variable Value Into Variable Name

Variable Variables in PHPi-1Every 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 of your php variable to be converted into the actual name of another variable. After a fair amount of hunting around the internet and getting sent off into PHP code hunting limbo for a few hours, I suddenly remembered that this was something that I had  found a solutio


Explanation of PHP Basic Syntax --New to PHPPhp is a language that is very much like writing c. The best feature of PHP versus c is that it is designed primarily to be used on WebPages -- allowing the author to intermingle their php code and the HTML on the same page. Being able to mix these two languages together provides a very flexible environment that allows the author to code some very nice dynamic content. PHP is called a server side scripting l

How To Use Dreamweaver

Dreamweaver - WISIWIGDreamweaver is a tool that arguably could be called the industry standard for web design.Dreamweaver, is an Adobe product that originally belonged to Macromedia. They sold out to Adobe a few years ago. I have been using Adobe/Macromedia Dreamweaver for about ten years. I am today using the Dreamweaver version that came packaged with Adobe CS 4. I started out with Dreamweaver 4. Since then Adobe has given this software a slightly different face and


Filezilla Ftp Client, FTP SERVER vs WsftpBy D.Shaun MorganWhile I was writing this article, about halfway through, I realized that it would be unfair to tell my readers about Filezilla without also mentioning another very good FTP client called WSftp. So, I backtracked and browsed over to website to take a look at the latest version. The fact is, when I first started building websites, WSftp was actually the first FTP client that I used. I don't know if Fil

Notepad Plus

Notepad++Download Notepad Plus Plus Notepad plus plus is an open source, free text editor. It is an ideal choice for many programming and scripting languages. Example - How to write c++ with Notepad Plus PlusExample - How to write HTML with Notepad Plus Plus

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 phpIn this tutorial we will look at the most commonly used file functions used in php. The examples below should be pretty familiar to the seasoned php scripter, but they are useful nonetheless. We will end this tutorial with a php script and an html form that will read the contents of a file into a string variable and output it into a textfield for editing. You can try the script out be

Stop Form Spam Captcha

PHP -- How to Protect My Email Form / Contact Form Against Spam BotsAuthor D.Shaun MorganRandom Name Fields to Stop SpambotRandom Name Fields to Stop SpambotExample Random Name Fields ScriptExample Message ScriptStopping Spam Bot With

Retreive Images Mysql Using Php

How to get images out of mysql database with php and use them on my webpagesRetrieving Images From Mysql Database With phpAuthor D.Shaun MorganPHP Version - PHP 5xMysql Version - 5Tutorial OutlineDownload Test ScriptsCreating a Test Mysql DatabasePhp Script to

How To Make Money Online

Making Money on the InternetSign up for this series of free money making articles Name Email Since you are reading this I am going to assume that you are looking to either start or improve a venture of starting or improving yo

Store Images Mysql Using Php

Storing Images in Mysql DatabaseTutorial OutlineCreating a Test Mysql DatabaseExample php Database FunctionExplanation of Database FunctionPhp Script to Load Images in Mysql DatabaseExplanation of Image ScriptSee Also

Php Example Post Array

Visual example of how PHP handles the super-global array variable "$_POST"Author D.Shaun MorganVersions and Skill LevelPHP Version - PHP 5xReader skill level - BeginnerXHTML 1.0 Transitional - interchangeable with HTML 4.0See AlsoHow can I pass a PHP variable from one page

Php Arrays

Passing PHP ArraysHow to pass php variable arrays between pages.Author Author D.Shaun MorganSee AlsoHow can I pass a PHP variable from one page to anotherIn PHP progra

How To Write Php Functions

Explanation of a Basic PHP FunctionWhat is a PHP function?In PHP a function represents a block of instructions that perform a task. A PHP Function allows the user to re-use blocks of script without having to rewrite all the code every time it's needed. This is useful for repetitive tasks that perform the same jobs over and over.PHP has a large number of built-in function

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 ( will mean the same for this tutorial.) forms to collect information from users. Those data are usually email addresses, names, birthdays, and sometimes private information like credit card info, SSN, and home addresses. (The scripts in this tutorial are not meant for processing security sensitive data. It is only intended to teach you h

Register Globals Long Arrays

Security, php.ini, register_globals and register_long_arraysAuthor D.Shaun MorganVersions and Skill LevelPHP Version - PHP 5xReader skill level - ALLTutorial Outlineregister_globalsregister_long_arraysSee AlsoPHP Tutorials

How To Install Php 5

How to Install PHP 5.x.x.x on WindowsThis 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 and working on your personal computer.This tutorial was written primarily for configuring a test server.Below is a list of what you need before you start trying to install PHP.An Apache server installed and running (

Php Passing Variables

Pass Variables from One Page to Another -- PHPTutorial Outline Passing PHP variables with $_POSTPassing PHP variables in links with $_GETPassing PHP variables without POST or GET | $_SESSION
Google Custom Search

Leave a Comment




Enter The Captcha:

Author: Keith | Website URL: |
Question what is the capimg.php file look like?? I understand the rest but not that function Thanks Keith
Author: CasTex | Website URL: |
Great tutorial for anti spam. Gonna try it on my blog
Author: allaboutdatingsites | Website URL: |
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: |
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: |
Thank you for this great script on stopping form spam!
Author: sai theja | Website URL: |
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: |
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: |
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: |
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: |
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: |
Your article is very good, very good with words, the sentence is smooth, rich in content.
Author: Darla | Website URL: |
Informative article, just what I needed.
Author: Carrol | Website URL: |
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.
Re: Admin
Yes it is ok to quote as long as you link back and give credit.
Author: Martha | Website URL: |
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: |
Good info. Lucky me I recently found your blog by chance stumbleupon .
I have book marked it for later
Author: Jovita | Website URL: |
Howdy I am so thrilled I found your blog, I really found you by accident, while I was looking on Digg for something else, Nonetheless I am here now and would just like to say kudos for a tremendous post and a all round enjoyable blog I also love the theme design , I don t have time to browse it all at the moment but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb job.
Author: tony | Website URL: |
i am testing your form : i want to copy this , if u dont mind can i pleeeease copy. thanks
Author: Veta | Website URL: |
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 - please link back to us.