CAPTCHA protection using PHP

Do you want to share WYSIWYG Web Builder tips, tricks, tutorials or useful HTML code? You can post it here...
(no questions or problems please, this section is not monitored by support).
Forum rules
This section is to share tips, tricks and tutorials related to WYSIWYG Web Builder.
Please do not post questions or problems here. They will not be answered.

PLEASE READ THE FORUM RULES BEFORE YOU POST:
viewtopic.php?f=12&t=1901
Post Reply
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

CAPTCHA protection using PHP

Post by kees »

This article describes how to add CAPTCHA protection with WebBuilder (for advanced users). It can be integrated in existing forms. The generated image looks like this:
Image
Requirements: PHP support with installed GD library.

Four files are needed:
- a PHP file that generates the captcha image
- a font file used in the captcha image
- a form page to enter the code shown on the captcha image
- a processing page that evaluates the generated and entered values
All four files should be placed in the same directory on your web server.

I The PHP file
1. Open Wordpad and insert this:

Code: Select all

<?php
$width  = 100;
$height = 38;
$font   = 'ITCBlkad.TTF';
$f_size = 35;

session_start();
$randomnr = mt_rand(1000, 9999);
$_SESSION['random_txt'] = md5($randomnr);
$im = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($im, 255, 255, 255);
$grey  = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, $width, $height, $black);
imagettftext($im, $f_size, 0, 22, 24, $grey , $font, $randomnr);
imagettftext($im, $f_size, 0, 15, 26, $white, $font, $randomnr);
header ('Content-type: image/gif');
imagegif($im);
imagedestroy($im);
?>
2. Save it onto your local harddisc and name it: captcha.php

II The font file
1. Open your fonts directory (usually C:\WINDOWS\Fonts\ ), locate Blackadder ITC (ITCBlkad.TTF) and copy this file to another place on your local harddisk. Be sure that the file is spelled exactly as in the above php file (case sensitive).

III The form page
You can add the captcha protection onto an existing form. In that case you can skip steps 1-2 below.
1. Draw a Form Area (or use an existing Form) and change the Form Properties to:
- Action: next_page.php or maintain the existing action file (*.php extension!)
- Method: POST
- Encoding type: empty (remove all text), or maintain the existing value
2. Be sure there is a Push Button on the Form Area. Bring up the Button Properties dialog and change it to:
- Button type: Submit
3. Put an Editbox onto the Form Area. Bring up its Editbox Properties dialog and change it to:
- Name: captcha_code
4. Draw a HTML Object (can be part of the Form Area) of 100 x 38 (w x h). Bring up its HTML Properties dialog and insert at HTML:

Code: Select all

<img src="captcha.php" alt="Click for new image" title="Click for new image" style="cursor:pointer" onclick="this.src='captcha.php?'+Math.random()">
5. Draw a File Publisher Object, open its File Publisher Properties dialog and add the two previous saved files: captcha.php and ITCBlkad.TTF

IV The processing page
You can add the captcha protection onto an existing processing page. In that case you can skip step 1 below.
1. Open a new page in WebBuilder or use an existing processing page.
- The name of this page equals the Form Action (step III-1), so in this example it is: next_page.
- The file extension should be: php (using the Page Properties dialog).
2. Bring up the Page HTML dialog and select Start of Page. Insert the next code (eventually before any existing code):

Code: Select all

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (isset($_POST['captcha_code'],$_SESSION['random_txt']) && md5($_POST['captcha_code']) == $_SESSION['random_txt']) {
    unset($_POST['captcha_code'],$_SESSION['random_txt']);
  }
  else {
    echo '<b>The entered code was wrong.</b><br>';
    echo '<a href="javascript:history.back()">Go Back</a>';
    exit;
  }
}
?>
Notes
1. You can choose another font for the captcha image. You can change the variables at the start of the script.
2. The file captcha.php can be replaced. There are many php scripts available for generating captcha images. Please make sure:
- that the file name is 'captcha.php'
- that the generated code is stored in a session variable as: $_SESSION['random_txt'] = md5($generated_code);
- that the dimensions (w x h) correspond with the HTML Object (step III-4)
3. This captcha solution was based on http://www.joriso.nl/verhaaltjes-webdev ... ptcha.html

Updated
25-11-07 Editbox name changed to 'captcha_code'
10-12-07 Added image and improved text
15-12-07 Improved html code (step III-4)
14-04-08 Simplified code (step IV-2)
07-09-08 Adjusted code at step IV-2. Now it works with the 'built-in' form processor too.
Last edited by kees on Sat Sep 06, 2008 10:50 pm, edited 7 times in total.
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

You can create your own error page. Use this code at step IV-2:

Code: Select all

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  header('Location: /index.html');
  exit;
}
if (isset($_POST['captcha_code'],$_SESSION['random_txt']) && md5($_POST['captcha_code']) == $_SESSION['random_txt']) {
  unset($_POST['captcha_code'],$_SESSION['random_txt']);
}
else {
  header('Location: ./wrong_code.html');
  exit;
}
?>
Notes:
- Replace ./wrong_code.html with your own error page.
- Your error page should have a hyperlink to javascript:history.back() . This allows the visitor to return to the form page.
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

This is an example of another captcha image code. It can be used as a replacement for 'captcha.php' in the original article. The generated image looks like this:
Image

How to proceed?
- Use this php code in step I-1:

Code: Select all

<?php
$width    = 100;
$height   = 38;
$font     = 'verdana.ttf';
$f_size   = 12;
$bg_color = array(240, 240, 240);
$chars    = 'ABCDEFGHKMNPQRSTUVWXYZ23456789';

session_start();
$im = imagecreatetruecolor($width, $height);
$bkgr = imagecolorallocate($im, $bg_color[0], $bg_color[1], $bg_color[2]);
imagefilledrectangle($im, 0, 0, $width, $height, $bkgr);
$code = '';
for($i = 0; $i < 5; $i++) {
  $code .= $chr = $chars[mt_rand(0, strlen($chars)-1)];
  imagettftext($im, $f_size, mt_rand(-35,35), 5+$i*(4/3*$f_size+2), mt_rand(4/3*$f_size, $height-(4/3*$f_size)/2), imagecolorallocate($im, mt_rand(0,192), mt_rand(0,192), mt_rand(0,192)), $font, $chr);
}
$_SESSION['random_txt'] = md5($code);
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
- The above php script uses verdana.ttf, so find this font file in step II-1.
- In step III-5 you should add the above two files to the File Publisher object: captcha.php and verdana.ttf

Notes
- The php script has some editable variables. You can play around with these as you please.
- The variable $bg_color holds the background color in decimal RGB notation.
- The variable $chars holds all characters that you want to allow in the captcha image.
Last edited by kees on Tue Apr 28, 2009 3:52 pm, edited 2 times in total.
User avatar
ely
 
 
Posts: 2
Joined: Sun Feb 25, 2007 3:17 pm
Location: Columbus, Ohio, USA
Contact:

I like this captcha code.

Post by ely »

I really like this code and just wanted to add a couple of things. Recently my website's contact form started getting spammed so I added this code and hopefully the problem will be solved.

I ran into a problem with some php setting in my hosting service that disabled session variables, so I wanted to make everyone aware of this in case they have problems getting this captcha code to work. I happen to be with one of the worst hosting services on the net, so I don't know how many other people might have this problem.

There is a PHP ini file on the server that controls how PHP works. Specific to session variables, there is a section, [session], that could break session variables that this captcha code depends on.

In PHP4, the default session save path statement is:

session.save_path = /var/php_sessions

In PHP5, the default session save path statement is commented out and looks like:

;session.save_path = "/tmp"

So you have to uncomment it by deleting the semicolon.

For both PHP4 & PHP5, make sure your configuration has the above session path, or change it to a path in your /public_html. Usually it will be something like ".../public_html/cgi-bin/temp". Depending on how your host is configured, you might need to know the complete path to your website's directory (also called Document Root). It might start something like: "/home/users/web/..."

So it was a bit of work actually getting my hosting service to work, but the code here was almost totally cut and paste. Because of how my server was configured, I had to change the location of my index page in the php processing code. From:

Code: Select all

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  header('Location: /index.html');
  exit;
To:

Code: Select all

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  header('Location: http://www.mywebsite.com/index.html');
  exit;
I used the verdana.ttf captcha image because the Blackaddr looked too hard to read.

Also, I made one small change to the php sendmail processor. I made it so the captcha would accept upper and lower case characters by changing the code from:

Code: Select all

if (isset($_POST['captcha_code'],$_SESSION['random_txt']) && md5($_POST['captcha_code']) == $_SESSION['random_txt']) {
  unset($_POST['captcha_code'],$_SESSION['random_txt']);
to:

Code: Select all

if (isset($_POST['captcha_code'],$_SESSION['random_txt']) && md5(strtoupper($_POST['captcha_code'])) == $_SESSION['random_txt']) {
  unset($_POST['captcha_code'],$_SESSION['random_txt']);
Hope this helps, and thanks for the original post.
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

This is an example of another captcha image code. It can be used as a replacement for 'captcha.php' in the original article. The generated image shows a simple addition sum like this:
Image
In this example 5 must be entered in order to submit the form.

How to proceed?
- Use this php code in step I-1:

Code: Select all

<?php
$width    = 100;
$height   = 38;
$font     = 'KOMIKAB_.ttf';
$f_size   = 25;
$bg_color = array(0, 0, 0);

session_start();
$im = imagecreatetruecolor($width, $height);
$bkgr = imagecolorallocate($im, $bg_color[0], $bg_color[1], $bg_color[2]);
$text = imagecolorallocate($im, mt_rand(50, 255), mt_rand(50, 255), mt_rand(50, 255));
imagefill($im,0, 0, $bkgr);
$number_1 = mt_rand(0, 5);
$number_2 = mt_rand(0, 5);
imagettftext($im, $f_size, 3, 7, 35, $text, $font, $number_1.'+'.$number_2.'=?');
$_SESSION['random_txt'] = md5((string)($number_1 + $number_2));
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
- The above php script uses KOMIKAB_.ttf, so find this font file in step II-1.
- This font is named 'Komika Boo'. Free download: http://www.urbanfonts.com/scripts/index ... poster.zip
- In step III-5 you should add the above two files to the File Publisher object: captcha.php and KOMIKAB_.ttf

Notes
- The php script has some editable variables. You can play around with these as you please.
- The variable $bg_color holds the background color in decimal RGB notation.
- This captcha was based on: http://phphulp.nl/php/scripts/9/1332/
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Re: this works BRILLIANTLY

Post by kees »

shaandeen wrote:this really works! ... thanks so much for this.
Thank you.
shaandeen wrote:... now i won't be getting invites to look at dodgy people doing whatnot!
No, this is an attempt to block automated spam bots. It will not stop people from sending unwanted messages.


CAPTCHA: Completely Automated Public Turing test to tell Computers and Humans Apart.

Turing test: http://en.wikipedia.org/wiki/Turing_test
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

Eddy wrote:...it redericts every time to the index.html page or another page what I type for header location.
Then it didn't pass the first check: was the script triggered by a form with 'post' method?
Eddy wrote:Have you tested the captcha code with the inbuild php formprosessor from the formwizard ?
Yes

I think the cause is in your form. What is the url of your form page?
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

Eddy, thanks for discovering that error.

I adjusted the form processing page code (step VI-2) to:

Code: Select all

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (isset($_POST['captcha_code'],$_SESSION['random_txt']) && md5($_POST['captcha_code']) == $_SESSION['random_txt']) {
    unset($_POST['captcha_code'],$_SESSION['random_txt']);
  }
  else {
    echo '<b>The entered code was wrong.</b><br>';
    echo '<a href="javascript:history.back()">Go Back</a>';
    exit;
  }
}
?>
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

1.
The 'Click for new image' function is working correctly!

The text doesn't show up on the form, but pops up as a tooltip when your mouse is over the image.

2.
The entered code in not verified, that's a problem.

I assume you used the built-in form processor from the Form Properties dialog. Did you add the php script at 'Start of Page' as described in step VI-2?
gp2727
 
 
Posts: 130
Joined: Fri Nov 04, 2005 12:40 pm
Location: USA

Post by gp2727 »

This small script will tell you if your server supports GD on your PHP Server, and if it does, it will list the specific components.
For example, some versions of PHP/GD have problems generating PNG files. You can use this script to know if you need to change
the script to generate a GIF instead, or if you just do not have support at all for GD.

Open a blank page in WB....Go to Menu Bar > Page > Page HTML > Beginning of Body Tab----Copy and Paste code listed below there. Now change your page properties to php....Name your page something easy to remember like gdtest.....Upload to your php server and open this page in a browser to check it.......

Code: Select all

<?php

/* Displays details of GD support on your server */

echo '<div style="margin: 10px;">';

echo '<p style="color: #444444; font-size: 130%;">GD is ';

if (function_exists("gd_info")) {

	echo '<span style="color: #00AA00; font-weight: bold;">supported</span> by your server!</p>';

	$gd = gd_info();
        
	foreach ($gd as $k => $v) {

		echo '<div style="width: 340px; border-bottom: 1px solid #DDDDDD; padding: 2px;">';
		echo '<span style="float: left;width: 300px;">' . $k . '</span> ';

		if ($v)
			echo '<span style="color: #00AA00; font-weight: bold;">Yes</span>';
		else
			echo '<span style="color: #EE0000; font-weight: bold;">No</span>';

		echo '<div style="clear:both;"><!-- --></div></div>';
	}

} else {

	echo '<span style="color: #EE0000; font-weight: bold;">not supported</span> by your server!</p>';

}

echo '<p>by <a href="http://www.dagondesign.com">dagondesign.com</a></p>';

echo '</div>';

?>
Output will look like this:

Image
bjlolmaugh
 
 
Posts: 63
Joined: Thu Nov 15, 2007 2:36 pm
Contact:

Post by bjlolmaugh »

Image Whooo Whooo !!!! I got it, I got it!!!

Kees, with your help of this very well layed out instruction, I finally was able to figure out how to add the Captcha Code to my forms that I prepared on Frontpage.

Thank you so much for all your hard work and detail. Image
Sincerely,

Barbara Lolmaugh
http://www.websitesbybarbara.com
Pete
 
 
Posts: 14
Joined: Sun Mar 30, 2008 6:44 pm

Post by Pete »

Hi


I had this CAPTCHA protection all working fine and now it seems to have stopped working properly!


The problem appears to be the text is not showing in the "1 + 2 = ?" box.

The background is shown & if I change the RGB() values the background colour will change.

Also, if I guess the answer(!) and get it correct, then the form proceeds ok - so it looks like it all configured (mostly) ok.

I've downloaded the TTF font back from the server and file-compared to a known good one incase of font corruption. Compares fine.

It *LOOKS* like the imagettftext() is not working properly. But I'm stuck. Any ideas?

Here's the image-display CAPTCHA.PHP
<?php
$width = 115;
$height = 38;
$font = 'akbar.ttf';
$f_size = 23;
$bg_color = array(0, 0, 0);

session_start();
$im = imagecreatetruecolor($width, $height);
$bkgr = imagecolorallocate($im, $bg_color[0], $bg_color[1], $bg_color[2]);
$text = imagecolorallocate($im, mt_rand(128, 255), mt_rand(128, 255), mt_rand(128, 255));
imagefill($im,0, 0, $bkgr);
$number_1 = mt_rand(0, 5);
$number_2 = mt_rand(0, 5);
imagettftext($im, $f_size, 3, 7, 35, $text, $font, $number_1.'+'.$number_2.'=?');
$_SESSION['random_txt'] = md5((string)($number_1 + $number_2));
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>


Many thanks
Pete
Pete
 
 
Posts: 14
Joined: Sun Mar 30, 2008 6:44 pm

Post by Pete »

Hi



with reference to the post above ..... ( imagettftext() not working ) ....


it's all sorted!

In case anyone else had this.......


I had to change the $font assignment
from
$font = 'akbar.ttf';
to
$font = dirname(__FILE__)."/akbar.ttf";

It seems the '/' before the font is important. Sometimes.
Hope this helps someone else


Pete
User avatar
chattd
 
 
Posts: 46
Joined: Wed Nov 26, 2008 7:03 pm

Re: CAPTCHA protection using PHP

Post by chattd »

kees wrote:*** Quoted message removed by moderator. ***
Hi Could you please help me i cant see the code in my form i have followed it to the letter i think,

http://www.glendower.co.uk/email/form/survey.php
http://www.glendower.co.uk/email/form/survey1.php
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

There is no need to quote the complete topic starting message. In most cases a link is enough, for instance: viewtopic.php?p=25616#25616

I looked into the html and saw no errors. It's clear that the file captcha.php does not work well.

Did you try any of the other examples?
- viewtopic.php?p=26875#26875
- viewtopic.php?p=41335#41335

If the other examples don't work too, it must be some setting at your web host.
User avatar
chattd
 
 
Posts: 46
Joined: Wed Nov 26, 2008 7:03 pm

Post by chattd »

Hi
Have it working now but it is saying the code you entered is wrong
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

The Edit Box name should be named captcha_code, but in your form is has an extra space (shown as #): captcha_code#.

Please remove that extra space.
User avatar
chattd
 
 
Posts: 46
Joined: Wed Nov 26, 2008 7:03 pm

Post by chattd »

Thank you so much for all your help
User avatar
iamafireman
 
 
Posts: 84
Joined: Mon May 26, 2008 2:41 am
Location: Tennessee

Post by iamafireman »

i have done this once and all went well, I tried it again for a different site and i cannt get the image to show.
http://ttmptest.info/Availability.php
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

I think you forgot to upload the font file.

Or the font file is not spelled correctly. The font name must be spelled exactly as in the script.
User avatar
iamafireman
 
 
Posts: 84
Joined: Mon May 26, 2008 2:41 am
Location: Tennessee

Post by iamafireman »

i have the font loaded its arial.ttf and thats what in captcha.php I have read through all 6 pages and still missing something
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

When I call captcha.php directly in the url bar it shows this error message:
Warning: imagettftext(): Could not read font in /home/content/d/o/n/donnajarrett/html/ttmptest/captcha.php on line 29

Warning: imagettftext(): Could not read font in /home/content/d/o/n/donnajarrett/html/ttmptest/captcha.php on line 31
So there must be something wrong with that font file.

When I call arial.ttf directly in the url bar a message indicates that the file is not a valid font file.
User avatar
Navaldesign
 
 
Posts: 862
Joined: Sat Mar 01, 2008 8:08 pm
Location: Italy
Contact:

Post by Navaldesign »

Only one captcha per page is possible, unless you modify the script.

However, i don't see how you have used more than one forms in the same page with Form Wizard. Did you use a separate script ?
www.dbtechnosystems.com
User avatar
Navaldesign
 
 
Posts: 862
Joined: Sat Mar 01, 2008 8:08 pm
Location: Italy
Contact:

Post by Navaldesign »

Ok, here is a fast one. It takes care of multipe departments (actually unlimited...) using a dropdowm.

You can test it at http://www.dbtechnosystems.com/wb5/contact_multiple.php

And you can download it at http://www.dbtechnosystems.com/wb5/mult ... tments.wbs

Please note that this script combines the method described in viewtopic.php?t=14938 with your requirements.

The code in the form page Start of Page should not be changed. Neither should the value of the hidden field.

The processing script is in the page confirm1.php
Please note that you will need to add here the email addresses. You will see the code:



$subject = 'New Submission from our Mulriple Department Website form';
$message = 'Values submitted from web site form to department: '.$_POST['department'];
$error_url = 'errorpage1.php';

$address['Sales'] = "sales@yourdomain.com";
$address['Warranty]' = "warranty@yourdomain.com";
$address['Manufacturing'] = "manufacturing@yourdomain.com";

$department_error = "Invalid department selection!<br>";// You can change this as required


Customize the parts in red as required.

Please note that i have used three departments in the listbox: Sales, Warranty, Manufacturing (taken from your page).

The values in the square brackets MUST be exactly as the values in the form combobox. The email addresses MUST be, for each one, the email address where you want the mail to be sent.

You can also cusomize the Subject, start of the message, and the error hat will be displayed (though it NEVER should) if the email address is not found due to a mistype.
Last edited by Navaldesign on Fri Jan 09, 2009 6:52 am, edited 1 time in total.
www.dbtechnosystems.com
User avatar
kees
 
Posts: 48
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees »

Yes, it will work.

One remark about your form: Using the built-in form processor, you should have a field named email (lower case). Yours is named Email.
User avatar
Navaldesign
 
 
Posts: 862
Joined: Sat Mar 01, 2008 8:08 pm
Location: Italy
Contact:

Post by Navaldesign »

If spammers have already got your email address from the site, and send you spam directly (not through your form) there is no way to stop them.

I suggest installing on your PC Windows Live Mail instead of the classic Outlook Express, as it has pretty good spam filters and gets continously updated with the newest spam servers lists.
www.dbtechnosystems.com
madjamonline
 
 
Posts: 51
Joined: Tue Jun 19, 2007 4:27 pm
Location: United Kingdom
Contact:

Post by madjamonline »

CAPTCHA is so that robots or non-humans cannot submit the form. However, I recon technology is developing to read images! If you just did a simple plain text question, the robot could read the html to find the answer!
User avatar
bry
 
 
Posts: 176
Joined: Fri Jan 11, 2008 8:44 pm

Post by bry »

A very clear example of why this is absolutely THE BEST FORUM on the internet. No where else will you find so many very, very smart people so willing to help beginners. WB continues to amaze me.
Post Reply