Create Captcha Image Verification

in
To avoid auto submitting application we can use captcha image verification. Using captcha method we make sure the form is filled by real human, not filed by a auto submitting robot.
1. Create captcha.php file. this file generate random number then display as image file. You can adjust width, height, bgcolor & forecoler of the image.
<?php
/* fornewbie.com
* create captcha image verification
* generate 5 digit random number 
*/
session_start();
$RandomStr =rand(10000, 99999); 	//Generate 5 digit random number
$imgWidth = 70;
$imgHeight = 30;
$bgColor = '#666666';
$frColor = '#FFFFFF';
 
$bgColorArr = sscanf($bgColor, '#%2x%2x%2x');
$frColorArr = sscanf($frColor, '#%2x%2x%2x');
$NewImage = imagecreatetruecolor($imgWidth, $imgHeight);
$bgColor = imagecolorallocate($NewImage, $bgColorArr[0], $bgColorArr[1], $bgColorArr[2]);
imagefill($NewImage, 0,0,$bgColor);
$frColor = imagecolorallocate($NewImage, $frColorArr[0], $frColorArr[1], $frColorArr[2]);
imagestring($NewImage, 5, 15, 5, $RandomStr, $frColor);// Draw a random string horizontally
$_SESSION['key'] = $RandomStr;// carry the data through session
header("Content-type: image/jpeg");// out out the image
imagejpeg($NewImage);//Output image to browser
?>
2. Create the Demo form (form.php)
<?
if (isset($_POST['Submit'])) {
	session_start();
	if ($_POST['code']==$_SESSION['key']) {
		$msg = "Verification Success";
	} else {
		$msg = "Verification Failed";
	}
}
?>
<html>
<head>
<title>Captcha Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
 
<body>
<form name="form1" method="post" action="">
  <table width="300" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td colspan="2">Captcha Demo </td>
    </tr>
    <tr>
      <td width="167">&nbsp;</td>
      <td width="133">
<? if (!isset($_POST['Submit'])) { ?>
<img src="captcha.php">
<? } else { ?>
&nbsp;
<? } ?>
</td>
    </tr>
    <tr>
      <td>Type Security Code </td>
      <td><input name="code" type="text" id="code"></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>
			<? if (isset($_POST['Submit'])) { ?>
			<?= $msg?>
			<? } ?>
			</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="Submit" value="Submit"></td>
    </tr>
  </table>
</form>
</body>
</html>
3. Try the code.
Demo

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.