Sunday, August 12, 2012

How can to implement Captcha with the refresh feature ( button )?

<?php
  session_start(); // start a session
  $image = imagecreate(50, 20); //create blank image (width, height)
  $bgcolor = imagecolorallocate($image, 0, 0, 0); //add background color with RGB.
  $textcolor = imagecolorallocate($image, 255, 255, 255); //add text/code color with RGB.
    $characters_on_image = 4;
    $possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
    $i = 0;
    $code = '';
    while ($i < $characters_on_image) {
    $code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
    $i++;
    }

  $_SESSION['captcha_code'] = ($code); //add the code to session
  imagestring($image, 10, 8, 3, $code, $textcolor); //create image with all the settings above.
  header ("Content-type: image/png"); // define image type
  imagepng($image); //display image as PNG
?>
Save this code in the file image.php

HTML File:
<table> <tr>
              <td valign="top">
<input type="text" name="txt_captcha_code" id="txt_captcha_code" value="" style="width:120px;" />
<img src="./cimage.php" id="captcha">
              <a href="JavaScript: new_captcha();">
                <img border="0" alt="" src="refresh.png" align="bottom">
              </a>
              </td> </tr></table>
JavaScript Code :
<script type="text/javascript">
function new_captcha()
{
var c_currentTime = new Date();
var c_miliseconds = c_currentTime.getTime();

document.getElementById('captcha').src = 'image.php?x='+ c_miliseconds;
}
</script>

No comments:

Post a Comment