Include this within the <head>
tag
<script type="text/javascript">
$(document).ready(function() {
// refresh captcha
$('img#captcha-refresh').click(function() {
change_captcha();
});
function change_captcha()
{
document.getElementById('captcha').src="captcha.php?rnd=" + Math.random();
}
});
</script>
And this code wherever you want the captcha image and refresh icon (get a suitable refresh image and rename it to refresh.jpg) to appear. Remember this code and the code above (within the <script>
tag) should be on the same page for the captcha to work.
<img src="captcha.php" alt="" id="captcha" />
Type the word:
<input name="user_captcha" type="text" id="captcha-code">
<img src="refresh.jpg" alt="" id="captcha-refresh" />
Then create a file called captcha.php (it generates captcha image in png format, as requested).
<?php
session_start();
header("Content-type: image/png");
$word_1 = '';
for ($i = 0; $i < 4; $i++)
{
$word_1 .= chr(rand(97, 122));
}
$_SESSION['random_number'] = $word_1;
$dir = "./";
$image = imagecreatetruecolor(165, 50);
$font = "whatever.ttf"; // font style you may give any you have / prefer
$color = imagecolorallocate($image, 0, 0, 0);// color
$white = imagecolorallocate($image, 255, 255, 255); // background color white
imagefilledrectangle($image, 0,0, 709, 99, $white);
imagettftext ($image, 22, 0, 45, 30, $color, $dir.$font, $_SESSION['random_number']);
imagepng($image);
?>
Then finally you have to check whether the user input and the text appearing in the captcha match or not by comparing $_POST['user_captcha']
and $_SESSION['random_number']
wherever you are passing the other values of the form.
N. B.: Do NOT forget to add session_start(); wherever you want the captcha image.