After we have completely designed the captcha system, we are ready to incorporate it into our web form. Below is a sample web form using the captcha script, with the file name captxt.php <?php session_start(); if (!$_POST['submit']) { //form not submitted, display form ?> <form action="<?php echo $SERVER['PHP_SELF']; ?>" method="post"> Complete name: <br /> <input type="text" name="name" size="50"> <br /> <img src="captxt.php" /> <br /> Type the security code above: <br /> <br /> <input type="text" name="captcha" size="10"> <input type="submit" name="submit" value="Submit"> </form> <?php } else { //form submitted if (!isset($_POST['name']) || trim($_POST['name']) == "") { die ('ERROR: Enter name'); } else { if (!($_POST['captcha']==$_SESSION['answer'])) { die ('ERROR: Enter the correct security code.Click here for <a href="http://localhost/captchatest.php">another captcha test</a>'); } } $name =$_POST['name']; $captcha =$_POST['captcha']; echo 'Your name is '.'<b>'.$name.'</b>'; echo '<br />'; echo 'Congratulations!!! You have correctly answered the security code which is '.'<b>'.$_SESSION['answer'].'</b>'; echo '<br />'; echo '<br />'; echo '<h1><b>This means you are human and not a BOT</b></h1>'; echo '<br />'; echo 'Click here for <a href="http://localhost/captchatest.php">another captcha test</a>'; } ?> Now I will provide you with a detailed explanation. One of the important things to note in the form script is the following: <?php session_start(); if (!$_POST['submit']) Without session_start(); you can't evaluate whether the captcha entered by the user is correct. As stated earlier, it should be placed in the first line of any PHP script using sessions. Also, take a look at this part of the code: <img src="captxt.php" /> <br /> Type the security code above: <br /> <br /> <input type="text" name="captcha" size="10"> The image SRC tag will display the captcha generated from captxt.php To test and evaluate whether the captcha entered is correct, see this code snippet: if (!($_POST['captcha']==$_SESSION['answer'])) { die ('ERROR: Enter the correct security code.Click here for <a href="http://localhost/captchatest.php">another captcha test</a>'); When the IF statement is true, the captcha is not entered correctly, thus displaying the error. Note that $_SESSION['answer'] contains the $number variable from the captcha script. To implement this, save captxt.php and form.php in the same path; for example, the root directory of your web server.
blog comments powered by Disqus |
|
|
|
|
|
|
|