PHP Captcha Sample

Captcha is a mechanism for eliminating or ensuring that web robots(webots) are not filtering (auto posting) into our comment or web forms, if you’ve kept a website with a comment box long enough online you must have had such experience. Here is the simple PHP program I wrote to help me cope with this when I was having such problem.


Note: each time the page is loaded the Captcha values randomly changed.

Download this Sample code (ZIP)

index.php

<?php
function randomizer($length) {
$arr = array("1","2","3","4","5","6","7","8","9","0","Q","W","E","R","T","Y","U",
"I","O","P","A","S","D","F","G","H","J","K","L","Z","X",
"C","V","B","N","M");
srand((float) microtime() * 1000000);
for($i = $length; $i > 0; $i--) {
$str .= $arr[rand(0, sizeof($arr))];
}
return $str;
}
$pin_var = randomizer(3);
?>

<html>
<head>
<title>Captcha Sample</title>
</head>

<body>
<b>POST COMMENT</b>
<form id="form1" name="form1" method="post" action="cap.php">
<table border="0" cellspacing="1" cellpadding="1">
<tr>
<td>Name
<input name="hiddenField" type="hidden" value="<?php print $article_id; ?>" /></td>
<td><input name="txtname" type="text" id="txtname" size="30" /></td>
</tr>
<tr>
<td>Email</td>
<td><input name="txtemail" type="text" id="txtemail" size="30" /></td>
</tr>
<tr>
<td>Comment </td>
<td><textarea name="txtcomment" cols="30" rows="5" id="txtcomment"></textarea></td>
</tr>
<tr>
<td>Captcha</div></td>
<td><?php print $pin_var; ?></td>
</tr>
<tr>
<td> Enter the captcha above </td>
<td><input name="txtval" type="text" id="txtval" size="15" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit" />
<input name="cap" type="hidden" id="cap" value="<?php print $pin_var; ?>" /></td>
</tr>
</table>
</form>
</body>
</html>

 

cap.php

<html>
<head>
<title>Captcha Sample</title>
</head>

<body>
<?php
$comm = strtoupper($_POST['txtval']);
$pin_var = $_POST['cap'];

if($comm != $pin_var){
print "Captcha not correct <a href=\"index.php\">try again</a>";
exit();
}else{
// Process the Form
print "Successful";
}
?>
</body>
</html>

 

 

Note: each time the page is loaded the Captcha values randomly changed.

 

Download this Sample code (ZIP)


Return to PHP Sample Main Page