Wednesday 15 July 2015

Web Tutorial: The CAPTCHA (Part 2/4)

You've created the front-end for your CAPTCHA. And also added a getCaptcha() function to call a PHP script tt_getcaptcha.php.

And today, we'll be creating the script for this little sucker. It will be incomplete and we'll need to come back to it sometime in the later parts of this tutorial.

First off, let's start by creating the file in a text editor.

tt_getcaptcha.php
<?php
session_start();
?>


This is important! The session_start() line creates  a session. We need to maintain a session in order to store the value for the CAPTCHA.

More on session_start(): (http://php.net/manual/en/function.session-start.php)
More on session variables in general:  (http://www.w3schools.com/php/php_sessions.asp)

<?php
session_start();

$_SESSION["captcha"]="";
?>


Here, we declare a key captcha in the system-defined array $_SESSION, which was in turn created with session_start(). This is initialized to an empty string.

<?php
session_start();

$_SESSION["captcha"]="";

for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;

}
?>


Now, we have a For loop! It iterates 6 times, as you can see. That's because we're going to generate a 6-dignit CAPTCHA sequence. You can fiddle with this number if you want, but this may mean you have to increase the length of your lblCaptcha div.

So here we generate a random number from 0 to 9, and assign it to the variable $captcha_char. $captcha_char is then appended to the $_SESSION["captcha"] variable.

One last line and we're ready to test!
<?php
session_start();

$_SESSION["captcha"]="";

for ($i=1;$i<=6;$i++)
{
    $captcha_char=rand(0,9);
    $_SESSION["captcha"].=$captcha_char;
}

echo $_SESSION["captcha"];
?>


This basically is the content that the getCaptcha() function is supposed to retrieve.

So run your code. When you load the page, do you see a random set of numbers in the box? Does the same happen if you click the "Get a new image" link?



There you go!

We now have a CAPTCHA generator. But it's still rather primitive, and there's a fair amount of work left to be done. In fact, after we complete the next bit of code, we'll need to improve this further.

Next

Comparing the CAPTCHA to user input. Another script coming right up.



1 comment: