Make Your own Captcha
You may see hundreds of captchas in various sites. Captchas use to protect from hacking programs and robots. Simply to identify the user is a human.
Working of a captcha as below.
1. Generate a random text
2. Text written to an image
3. Text stored in session
4. Image displays to the user
5. User enters the code
6. User entered code is checked with the stored text
7. If they match then continue
Let’s make your own simple captcha now. In here we will make a captcha which has 5 numbers. So that we use rand() function in php.
For example rand(5, 15)will generate random number between 5 and 15. In our case we need a 5 digit number. So we can use this function as rand(10000, 99999).
Now we have the string and next step is to write it an image. So that we’re going to use my favorite GD library of image functions in PHP. Imagecreatefrompng() function is use to create a image start from a existing png image. In here we already have the “captcha.png” and the text will draw on that image.
$captcha = imagecreatefrompng("captcha.png")
Colors are allocate as follows in RGB,
$black = imagecolorallocate($captcha, 0, 0, 0)
Finally we have to write the text to the image which is made easy with imagestring()
imagestring($captcha, 5, 20, 10, $string, $black)
To view the image
<img xsrc="captcha.php" border="0">
Next thing is to store the text in session.
$_SESSION[‘text’] = $string
Finally to compare the correct code with the user given text, use following code
<?php
session_start();
If($_POST['text'])= $_SESSION['text'])
{
echo 'You entered the code correctly';
}else{
echo 'You entered the code wrong';
}
?>
The complete code of our simple captcha as follow.
File name:Index.html
<html>
<body>
<form action="compare.php" method="post">
<p>Enter the code below</p>
<img src="captcha.php" border="0"><br>
<input type="text" name="text" />
<p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>
File name: captcha.php
<?php
header("Content-type: image/png");
session_start();
$string=rand(10000, 99999);
$captcha = imagecreatefrompng("captcha.png");
$black = imagecolorallocate($captcha, 0, 0, 0);
imagestring($captcha, 5, 25, 5, $string, $black);
imagepng($captcha);
$_SESSION['text'] = $string;
?>
File name: compare.php
<?php
session_start();
If($_POST['text']== $_SESSION['text'])
{
echo 'You entered the code correctly';
}else{
echo 'You entered the code wrong';
}
?>
Last edited by Tharaka Deshan; 01-14-2010 at 05:35 AM.
|