Posts Tagged ‘captcha’

Using Asirra in ASP.Net MVC

Tuesday, January 13th, 2009

A simple helper to integrate and validate Asirra in ASP.Net MVC.

People use CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) to prevent their websites from automatic posting. Asirra is such a technique which can be used to protect websites from automatic posting.

What is Asirra

Asirra is a human interactive proof that asks users to identify photos of cats and dogs. It’s powered by over three million photos from Petfinder.com.

Asirra (Animal Species Image Recognition for Restricting Access) is a HIP that works by asking users to identify photographs of cats and dogs. This task is difficult for computers, but people can accomplish it quickly and accurately. You can learn more about Asirra here MSR Asirra: A Human Interactive Proof.

How to use it

You can easily use it in your website. You can find details of how to use it from MSR Asirra Project – Installation.

I have prepared a helper to use it in ASP.Net MVC application and I will show how to use this helper in your website. First look at the following sample pictures of user registration form.

Integrate Asirra challenge

Import the namespace at the top of your view aspx page.

<%@ Import Namespace="Valentica.Helpers" %>

Then call the GenerateAsirra() method of the helper where you like to put the Asirra challenge. For example:

<%= AsirraHelper.GenerateAsirra() %>
 
// Or
// You can control where the big version of the photos appear by
// changing EnlargedPosition to Top, Bottom, Left, or Right
<%= AsirraHelper.GenerateAsirra(EnlargedPosition.Right) %>
 
// Or
// You can control the aspect ratio of the box by changing rowsPerCell value 
<%= AsirraHelper.GenerateAsirra(4) %>
 
// Or
<%= AsirraHelper.GenerateAsirra(EnlargedPosition.Right, 4) %>

Perform client side validation

To validate Asirra in client side use the following steps.

Step 1:

Call MySubmitForm() method in onsubmit properties of your form. For example:

<form id="mainForm" action="/Account/Register" method="post"
         onsubmit="return MySubmitForm();">

Step 2:

Then simply use the following javascript code.

<script type="text/javascript">
    var passThroughFormSubmit = false;
 
    function MySubmitForm()
    {
         if (passThroughFormSubmit) {
              return true;
         }
         // Do site-specific form validation here, then...
         Asirra_CheckIfHuman(HumanCheckComplete);
         return false;
    }
 
    function HumanCheckComplete(isHuman)
    {
         if (!isHuman)
         {
              alert("Please correctly identify the cats.");
         }
         else
         {
              passThroughFormSubmit = true;
              formElt = document.getElementById("mainForm");
              formElt.submit();
         }
    }
</script>

Server side validation

In your action field together with other validation use IsValidate() method of AsirraHelper.

// Validate Assira Here
if (AsirraHelper.IsValidAsirra(Request.Form["Asirra_Ticket"]))
{
    ModelState.AddModelError("Asirra_Ticket", "Asirra Invalid");
}

Try it now!

References

1. MSR Asirra: A Human Interactive Proof
2. MSR Asirra Project – Installation

Source Codes

You can download full source code from here. Asirra Sample

convert this post to pdf.

Captcha Plugin in CodeIgniter

Friday, May 23rd, 2008

CAPTCHACompletely Automated Public Turing test to tell Computers and Humans Apart. It is used in webpages to protect your page from automatic posting from outside of the site. CodeIgniter framework has a plugin named “captcha_pi.php” in plugins folder. Here I’ve demonstrated an example how to use this captcha plugin in your website built in CodeIgniter framework.

Make a controller named "captcha.php" and place in “controllers” folder. This controller is as follows:

<?php
class Captcha extends Controller
{
  public function __construct()
  {
    parent::Controller();
 
    $this->load->model('captcha_model');
 
    session_start();
  }
 
  public function index()
  {
    if(empty($_POST))
    {
      $captcha = $this->captcha_model->generateCaptcha();
 
      $_SESSION['captchaWord'] = $captcha['word'];
 
      $data['captcha'] = $captcha;
 
      $this->load->view('show_view', $data);
    }
    else
    {
      //check captcha matches
      if(strcasecmp($_SESSION['captchaWord'],
                   $_POST['confirmCaptcha']) == 0)
      {
        $this->load->view('success_view');
      }
      else
      {
        $this->load->view('failure_view');
      }
    }
  }
}
?>

Here I’ve made a model named "captcha_model" that has a method generateCaptcha(), which generates the captcha using CodeIgniter captcha plugin and returns the array. Captcha word is saved in session and after submitting the form this session word is compared with the posted word for matching.

If matches which is in (strcasecmp($_SESSION['captchaWord'], $_POST['confirmCaptcha']) == 0), then success is shown. Otherwise failure is shown. Here I’ve used strcasecmp() function of php to compare the word as case-insensitively. If u want user to enter the captcha words as they are shown (i.e. capital letter in capital and small letter in small), then you can use strcmp() function.

The captcha_model.php is as follows:

<?php
class Captcha_model extends Model
{
  private $vals = array();
 
  private $baseUrl  = 'http://localhost/captchademo/';
  private $basePath = 'D:/apache2triad/htdocs/captchademo/';
 
  private $captchaImagePath = 'tmp/captcha/';
  private $captchaImageUrl  = 'tmp/captcha/';
  private $captchaFontPath  = 'c:/windows/fonts/verdana.ttf';
 
  public function __construct($configVal = array())
  {
    parent::Model();
 
    $this->load->plugin('captcha');
 
    if(!empty($config))
      $this->initialize($configVal);
    else
      $this->vals = array(
                 'word'             => '',
                 'word_length'   => 6,
                 'img_path'       => $this->basePath
                                 .  $this->captchaImagePath,
                 'img_url'        => $this->baseUrl
                                 . $this->captchaImageUrl,
                 'font_path'      => $this->captchaFontPath,
                 'img_width'      => '150',
                 'img_height'     => 50,
                 'expiration'      => 3600
               );
  }
 
  /**
   * initializes the variables
   *
   * @author     Mohammad Jahedur Rahman
   * @access     public
   * @param     array     config
   */
  public function initialize ($configVal = array())
  {
    $this->vals = $configVal;
  } //end function initialize
 
  //---------------------------------------------------------------
 
  /**
   * generate the captcha
   *
   * @author     Mohammad Jahedur Rahman
   * @access     public
   * @return     array
   */
  public function generateCaptcha ()
  {
    $cap = create_captcha($this->vals);
 
    return $cap;
  } //end function generateCaptcha
}
?>

You have to change the $baseUrl, $basePath, $captchaImagePath, $captchaImageUrl and $captchaFontPath etc. To store the captcha images at first I’ve created a folder “tmp” and sub-folder “captcha” in the main directory where index.php exists. If u run on server be sure this two folder are given write permission.

By default, Captcha plugin generates 8 words in length. But I desire to very this length. So, I’ve made a little change in this plugin. In line 156 of "captcha_pi.php" there was

$defaults = array('word' => '', 'img_path' => '',
                 'img_url' => '', 'img_width' => '150',
                 'img_height' => '30', 'font_path' => '',
                 'expiration' => 7200);

which I made

$defaults = array('word' => '', 'word_length' => 8,
                 'img_path' => '', 'img_url' => '',
                 'img_width' => '150', 'img_height' => '30',
                 'font_path' => '', 'expiration' => 7200);

Next, in line 226, there was

for ($i = 0; $i < 8; $i++)

which I made

for ($i = 0; $i < $word_length; $i++)

Now if u pass word_length as parameter then it will generate captcha image of word length as you specify.

Captcha

You can download the whole package from here.

captchademo

convert this post to pdf.