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
User avatar
kees
 
Posts: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

CAPTCHA protection using PHP

Post by kees » Sat Nov 24, 2007 5:47 pm

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: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees » Sun Dec 02, 2007 12:35 am

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: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees » Sun Dec 16, 2007 12:12 am

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: 14
Joined: Sun Feb 25, 2007 3:17 pm
Location: Columbus, Ohio, USA
Contact:

I like this captcha code.

Post by ely » Wed Mar 19, 2008 5:24 pm

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: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees » Wed Apr 30, 2008 10:50 pm

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: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Re: this works BRILLIANTLY

Post by kees » Tue Jul 08, 2008 11:05 pm

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: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees » Sat Sep 06, 2008 9:24 pm

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: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees » Sat Sep 06, 2008 11:06 pm

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: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees » Mon Sep 08, 2008 10:07 pm

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: 163
Joined: Fri Nov 04, 2005 12:40 pm
Location: USA

Post by gp2727 » Sat Oct 18, 2008 4:35 pm

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: 73
Joined: Thu Nov 15, 2007 2:36 pm
Contact:

Post by bjlolmaugh » Tue Oct 28, 2008 7:56 pm

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: 2
Joined: Sun Mar 30, 2008 6:44 pm

Post by Pete » Wed Nov 05, 2008 11:51 am

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: 2
Joined: Sun Mar 30, 2008 6:44 pm

Post by Pete » Wed Nov 05, 2008 2:04 pm

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: 47
Joined: Wed Nov 26, 2008 7:03 pm

Re: CAPTCHA protection using PHP

Post by chattd » Sat Jan 03, 2009 6:12 pm

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: 49
Joined: Mon May 23, 2005 7:36 pm
Location: Soest - NL

Post by kees » Sat Jan 03, 2009 7:03 pm

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.

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest