Web Info and IT Lessons Blog...

Tuesday, 28 April 2015

Simple Captcha in PHP

The previous lesson of PHP Lessons Series was about writing text to an image and in this lesson we will learn to create a simple captcha in PHP.

Simple PHP Captcha

In this lesson we will use two separate php files to create a captcha. In one file we will handle the html and php part of the captcha and in the other file we will generate a captcha image. Let us have a look at our captcha image file first:


/* captcha-image.php file */
<?php
session_start();
header('Content-type: image/jpeg');
$text=$_SESSION['text'];
$font_size=30;
$image_width=150;
$image_height=50;
$image=imagecreate($image_width,$image_height);
imagecolorallocate($image,255,255,255);
$text_color=imagecolorallocate($image,0,0,0);
imagettftext($image,$font_size,0,15,40,$text_color, 'font.ttf',$text);
imagejpeg($image);
?>

The above code will create a captcha image with a random 4 digit number written to it. The random number to write to the captcha image is set in a session variable ($_SESSION['text']) in the php part of the other php file. Now let us code our other php file:


/* index.php file */
<?php
session_start(); 
if(!isset($_POST['captchaText'])){
 $_SESSION['text']=rand(1000,9999);
}else{
 $captchaText = $_POST['captchaText'];
 if($_SESSION['text'] == $captchaText){
  echo '<b style="color:green;">You entered correct value!</b>
                      <a href="index.php">Try Again!</a><br><br>';
 }else{
  echo '<b style="color:red;">You entered wrong value!</b>
                      <a href="index.php">Try Another!</a><br><br>';
 }
}
?>
<img src="captcha-image.php" border="1" /><br><br>
<form action="#" method="POST">
Enter the value in captcha image:<br>
<input type="text" name="captchaText" />
<input type="submit" value="Submit" />
</form><br /><br />

In the html part of the above code we show the captcha image created in the captcha-image.php file and we have an html form element to post the value entered in the text field to php. In the php part of the code we set the session variable for random text if the form is not submitted yet i.e


$_SESSION['text']=rand(1000,9999);

If the form submit button is clicked then we compare the value posted in the text field and the value set in session variable to check if the captcha image value matches the user input value of the captcha.

Stay tuned for more lessons...

Related Posts
How to create an image in PHP?
Drawing image patterns using imagesetpixel() in PHP
Convert a string to an image in PHP
Convert an image to a string in PHP
Write text to an image in php

No comments:

Post a Comment