Form validation with Captcha image



by Administrator author list

 

The next big task is to create a form using the image we just generated and process the visitor inputs. As you may remember we have stored the security code in a session variable so we need to start a session first. As next step we can check if the form was submitted or not. If not then we can display a form. Here you can create as complex form as you want. The only important thing is that you need to add an input text field for the security code and of course you need to display the Captcha image. This last step is very simple; just use our first PHP – which generates the image - code as image source.  The form should look like this:

 

      <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
        <table width="400">
          <tr>
            <td>Security code: 
               <input class="text" name="secCode" type="text" size="10" />
            </td>
            <td>
               <img src="securityCode.php" alt="security code" border="1" />
            </td>
          </tr>
          <tr>
            <td colspan="2" align="center"><br/>
               <input class="text" type="submit" name="submitBtn" value="Send" />
            </td>
          </tr>
        </table>  
      </form>

 

Now back to the form processing part of the script. First we need to check the existence of the security code and if it was submitted then we convert it to lowercase to make it case insensitive. If you want to make a case sensitive Captcha solution then you also need to modify the image generation script and remove the strtolower function.

 

It’s time to check if the security code we have saved in the session is the same as the security code typed by the visitor.  If it is valid then we clean the session variable and set a result variable. This result variable will show us if we need to display the form again or not. You need to call your own business logic inside the valid case.

 

The complete check procedure is the following:

 

<?php
   
if (isset($_POST['submitBtn'])){
      
$secCode = isset($_POST['secCode']) ? strtolower($_POST['secCode']) : "";
      if (
$secCode == $_SESSION['securityCode']) {
         echo 
"<p>The result code was valid!<br/></p>";
         unset(
$_SESSION['securityCode']);
         
$result true;
      }
      else {
         echo 
"<p>Sorry the security code is invalid! Please try it again!</p>";
         
$result false;
      }
   }
?> 

 

That’s all, we are ready!

 



article index
page 1 : untitled page
page 2 - current : Form processing
page 3 : Complete code


Tags: php captcha tutorial

Php Toys - 2006 - Php resources, scripts and tutorials - Privacy Policy
Insurance Index - Tutorial collection - Forex trading, brokers, reviews - Mortgage payment calculator
{THEMEDISCLAIMER}
Render time: 0.1281 sec, 0.0186 of that for queries. DB queries: 25.