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
CSS
Software
Funny
Privacy Policy
JavaScript
Category: php
.

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

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

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

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 p

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

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 disp

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

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;

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

how to unzip files on your free hosting account

Uzipping Files on Your Web ServerIf 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 of features. One feature that I could not find on Godaddy.com free hosting accounts was a utility tha

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

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 tryin

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

how to turn variable value into variable name

Variable Variables in PHPEvery 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.

what-is-php

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 t

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

Filezilla

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

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++ w

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 nonethel

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 Fi

retreive images mysql using php

How to get images out of mysql database with php and use them on my webpagesAuthor D.Shaun MorganPHP Version - PHP 5xMysql Version - 5Tutorial OutlineC

store images mysql using php

Storing Images in Mysql DatabaseTutorial OutlineCreating a Test Mysql DatabaseExample php Database FunctionExplanation of Database Function

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 Transition

php arrays

Passing PHP ArraysHow to pass php variable arrays between pages.Author Author D.Shaun Morgan

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

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

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 Outline

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 configuri

php passing variables

Pass Variables from One Page to Another -- PHPTutorial Outline Passing PHP variables with

.

Leave a Comment

stop_form_spam_captcha.php



Comment:


captcha

Enter The Captcha:


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: Jovita | Website URL: http://cheapcaptcha.com |
Comment:
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: 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.