How TO create a random alpha-numeric CAPTCHA and reload it with AJAX without refreshing page.

dtrick captcha dtrick captcha[/caption]

captcha.php

<?php
session_start();
function captcha($code) {
putenv(‘GDFONTPATH=’ . realpath(‘.’));
$font = ‘avgardd.ttf’;
$char_width = 32;
$height = 48;
$full_width = $char_width*4;
$output_img = imagecreatetruecolor($full_width, $height);
$background_img = imagecreatefrompng(‘background.png’);
imagecopy($output_img, $background_img, 0, 0, mt_rand(0, 160), mt_rand(0, 48), 256, 96);
for($i=0;$i<strlen((string)$code);$i++) {
$char = $code{$i};
$img = imagecreatetruecolor($char_width, $height);
imagealphablending($img, false);
imagesavealpha($img, true);
$text_colour = imagecolorallocate($img, mt_rand(140, 195), mt_rand(54, 65), mt_rand(40, 128));
$bg_colour = imagecolorallocatealpha($img, 255, 255, 255, 127);
imagefilledrectangle($img, 0, 0, $full_width, $height, $bg_colour);
imagettftext($img, mt_rand(18, 20), mt_rand(0, 15), 6, 30, $text_colour, $font, $code{$i});
imagealphablending($img, true);
imagecopy($output_img, $img, $i * $char_width + mt_rand(0, 5), mt_rand(0, 15), 0, 0, $char_width, $height);
imagedestroy($img);
}
header(‘Content-Type: image/png’);
header(‘Cache-control: no-cache, no-store’);
imagepng($output_img);
imagedestroy($output_img);
}
$rand = mt_rand(0, 46655);
$code = base_convert($rand,10,36);
$code = sprintf(“%03s”,$code);
$code = preg_replace(‘/[iloq01]/’, ‘n’, $code);
$code = strtoupper($code);
$_SESSION[‘code’] = $code;
captcha($code)
?>

form in which you have to place captcha.
form.php

<form>

<label>Captcha<span style=”color:red”>*</span></label>
<br />
<img id=”captcha_img” src=”captcha.php” /> <br/>
<a href=”#” onclick=”document.getElementById(‘captcha_img’).src=’captcha.php?img=’ + Math.random(); return false”>Reload Captcha</a>
<br />
<input type=”text” id=”user_captcha” name=”txtcaptcha” class=”form-control” placeholder=”Enter Captcha code” required data-errormessage-value-missing=”Please enter Captcha” data-errormessage-type-mismatch=”Invalid!”>
<br/>

</form>

<!—————call to ajax to reload captcha without refreshing page——————->

function refresh_captcha()
{
$.ajax({
type:”GET”
url: “/captcha_images.php?width=120&height=40&code=$code”?>’
success: function(msg)
{
document.getElementById (“captcha_img”).src = msg;
},
error:functon(){alert(“some error occured”);}
});

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s