php resource centre

  • about
  • articles
  • tutorials
  • resources
  • certification
Home

Primary links

  • About
  • Articles
  • Tutorials
  • Resources
  • Certification

Securing forms using captcha.

admin — Sat, 22/11/2008 - 10:55am

Securing forms usng captcha has become a common practise nowadays.
Here is a simple method to do this.

Securing forms usng captcha has become a common practise nowadays.
Here is a simple method to do this.

There are 4 files required for this :
1. captcha.png - This is the image file which will be the base for the Captcha.
2. captcha.php - the code for generating the random string and embedding it in the base image is in this file.
3. form.html - the file with the form in whcih the captcha will be added
4. arial.ttf - a font file which will be used for the string written on teh base image.

Following is the code in the captcha.php file :
<?php
session_start(); //start session

/* Code to generate random number /*
function newNum(){
    $num=rand(0, 100);
    return $num;
}

$string=$_SESSION['cap_key'];
$captcha = imagecreatefromgif('captcha.gif');
$black = imagecolorallocate($captcha, 0,0,0);
$line = imagecolorallocate($captcha,233,239,239);
$font = 'arial.ttf';

/* Each letter in teh string is written at a certain angle using the following */
function randomline($captcha,$line){
    imageline($captcha,newNum(),newNum(),newNum(),newNum(),$line);
}
for ($i = 0; $i <= rand(40,50); $i++) {
    randomline($captcha,$line);
}
/* generate and write the string onto the image using the font */
imagettftext($captcha, 20, rand(0,10), 5, 40, $black, $font, $string);
header('Content-type: image/gif');
imagegif($captcha);
?>

Now, we need to call the above captcha in the form. For this add the following to your form.

<img src="captcha.php" alt="captcha" />
<input type="text" name="code" id="code">
<input type="hidden" name="captchaid" value="<?=$_SESSION['cap_key']?>">

All you need to do now using Javascript code is the validate what is input in the textfield 'code' is the same as what is stored in the hidden variable 'captchaid'.

Thats it !

  • Articles
  • Login to post comments

User login

  • Request new password

Follow Us

Who's online

There are currently 0 users and 1 guest online.

Who's new

  • Nisha
  • linnaeus
  • Yameen
  • TalleyReedy
  • admin

Follow vipin7873 on Twitter

  • about
  • articles
  • tutorials
  • resources
  • certification

copyright © 2010 Vipin Chandran