You are here:Home » PHP » Simple PHP Captcha Script

Simple PHP Captcha Script


PHP Image & Captcha

In this tutorial, I will teach you how to validate a simple captcha image. It requires PHP GD2 extension. In case you are testing on localhost, ensure it is enabled first. We will create only two files- NewImage.php which generates the image, and saves value to session, and index.php that does validation
.

NEWIMAGE.PHP

<?php
session_start();
$string = md5(rand(0,99));
$new_string = substr($string, 17, 6);
$_SESSION['magic']=$new_string;
//imagecreate(width, height) of background
$im = imagecreate(90, 25);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $black);
//imagestring("","", margin-left, margin-top, $string, $string_color)
imagestring($im, 5, 20, 5, $new_string, $white);
header("Content-Type: image/png");
imagepng($im);
imagedestroy($im);
?>

INDEX.PHP

<?php
session_start();
global $msg;
if(isset($_POST['rand'])){
    $rand=$_POST['rand'];

    if ($_SESSION['magic'] == $rand){
    $msg= "<font color='green'>Verified Ok</font>";
    }else{
    $msg= "<font color='red'>Incorrect</font>";
    }
}
?>

<html>
<head>
<title>Simple PHP Captcha by Ohwofosirai Desmond</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><input type="image" src="NewImage.php" class="captcha"/></p>
<p><label for="captcha"><em>Enter The Captcha Below:</em></label></p>
<p><input name="rand" type="text" value="">&nbsp;&nbsp;<?php echo $msg; ?></p>
<p><input type="submit" value="submit"></p>
</form>
</body>
</html>
Simple PHP Captcha, Captcha Verification, Captcha Script

0 comments:

Post a Comment