Thursday 12 April 2012

How to implement CAPTCHA in PHP?

CAPTCHA is used to prevent spam abuse on the websites.

If we have a public submission form on our website (contact Us page), we can use CAPTCHA.
We can discuss how we can implement CAPTCHA in PHP

1. Create a php file that generates image.(say CaptchaImages.php)

<?php
session_start();
class CaptchaSecurityImages {
    var $font = 'Teen Bold.ttf';
    function generateCode($characters) {
        /* list all possible characters, similar looking characters and vowels have been removed */
        $possible = '23456789bcdfghjkmnpqrstvwxyz';
        $code = '';
        $i = 0;
        while ($i < $characters) {
            $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
            $i++;
        }
        return $code;
    }

    function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
        $code = $this->generateCode($characters);
        /* font size will be 75% of the image height */
        $font_size = $height * 0.75;
        $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
        /* set the colours */
        $background_color = imagecolorallocate($image, 255, 255, 255);
        $text_color = imagecolorallocate($image, 20, 40, 100);
        $noise_color = imagecolorallocate($image, 100, 120, 180);
        /* generate random dots in background */
        for( $i=0; $i<($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for( $i=0; $i<($width*$height)/150; $i++ ) {
            imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height),

$noise_color);
        }
        /* create textbox and add text */
        $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext

function');
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        $_SESSION['security_code'] = $code;
    }
}
$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '6';
$captcha = new CaptchaSecurityImages($width,$height,$characters);
?>



2. Copy paste “Teen Bold.ttf” font in the same directory as the CaptchaImages.php file. (Alternatively you can replace the line var $font = ‘Teen Bold.ttf’; with the name of whatever font you want to use)
You can download the font from http://www.webpagepublicity.com/free-fonts-t.html#Free%20Fonts


3. Put the below code in the form.
    <input id="security_code" name="security_code" type="text" />
    <img src="CaptchaImages.php?width=100&height=40&characters=5" />
    (you can specify the width and height of the image)

4. Put the below code in the form . It check the generated captcha image with the image you have submitted in the text box.

   <?php
      session_start();
   if( isset($_POST['submit'])) {
   if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {      
        unset($_SESSION['security_code']);
           if($_SERVER["REQUEST_METHOD"] == "POST"){
             // process email
        }
     } else {
            // validation message
               unset($_SESSION['security_code']);
   }
  }
?>

************************************************************************************
Php example which contains the contact form:


 <?php
 error_reporting(0);
 session_start();
if( isset($_POST['submit'])) {
   if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
       
        unset($_SESSION['security_code']);
           if($_SERVER["REQUEST_METHOD"] == "POST"){
               $to = "someone@example.com";
            $subject = $_POST['subject'];
            $message = $_POST["textarea"];
            $from = $_POST["email"];
            $headers = "From:" . $from;
            mail($to,$subject,$message,$headers);
        }
     } else {
        echo "<br/>";
        echo "<b>";
        echo "<div align='left'>";
        echo "<font color='red'>". 'Sorry, you have provided an invalid security code'."</font>";
        echo "</div>";
        echo "</b>";
        unset($_SESSION['security_code']);
   }
 
}
?>
 <form name="form1" id="form1" method="post" action="">
                                  <table border="0" width="350" style="font-size:12px;">
                                    <tbody>
                                    <tr>
                                      <td>
                                        <label for="label"> <strong>Email</strong></label>
                                        <label for="label">:</label>
                                       *</td>
                                       <td >
                                          <input type="text" id="email" name="email">
                                       </td>
                                    </tr>
                                    <tr>
                                      <td height="28"><label for="txtemail"> <strong>Subject:</strong>
                                      </label>
                                       *</td>
                                       <td height="28">
                                          <input type="text" id="subject" name="subject">
                                      </td>
                                    </tr>
                                                                       <tr>
                                      <td height="30">
                                      <label for="label2"> <strong>Message:</strong></label>
                                       *</td>
                                       <td>
                                          <textarea id="textarea" name="textarea" rows="5" cols="17"></textarea>
                                     </td>
                                    </tr>
                                         <tr> </tr>
                                    <tr>
                                      <td>
                                      <label for="security_code"><Strong>Security Code:</Strong> </label>
                                      *
                                    <br/></td>
                                    <td>
                                            <input id="security_code"

name="security_code" type="text" /><br />
                                        </td>
                                       
                                    </tr>
                                    <tr>
                                      <td><div align="left">
                                          <img src="CaptchaImages.php?width=140&height=40&characters=5" />
                                           
                                        </div></td>
                                    </tr>
                                  
                                  
                                   
                                    <tr>
                                      <td height="32"><div align="center"><strong></strong></div></td>
                                    </tr>
                                    <tr>
                                      <td><div align="center">
                                          <input type="submit"   value="Send Message" name="submit">
                                      </div></td>
                                    </tr>
                                  </tbody></table>
                                </form>

No comments:

Post a Comment