Simple PHP Captcha Tutorial
1/05/2013I've made this dead simple. This is the easiest (yet secure), most customizable captcha you will likely find. It simple spits out random math questions using numbers 1 through 5 (1+3, 4+2, 5+3, etc). Note: the PHP code below goes in a seperate page thats called by the form (FYI action="simple-php-captcha-formmail.php"). This is also where the rest of your PHP validation would go. I have the error message and the success message redirecting to seperate pages. YOU can do it however you wish by editing the code below to your liking. If you want JS validation to boot, then grab it from here.
The PHP
<?php // Clean Captcha: random numbers 1 through 5 (1+3, 4+2, 5+3, etc) session_start(); if (!isset($_SESSION['num1']) || !isset($_SESSION['num2'])) { // No known session cannot validate captcha header( "Location: simple-php-captcha-error.php" ); exit; } $sum = (int)$_SESSION['num1'] + (int)$_SESSION['num2']; if (isset($_POST['captcha']) && (int)$_POST['captcha'] !== $sum) { // Captcha given but incorrect header( "Location: simple-php-captcha-error.php" ); exit; } else { // Captcha correct show new one next time unset($_SESSION['num1'], $_SESSION['num2']); } // Test if email sent mail('your@email.com', 'test', 'email'); header( "Location: simple-php-captcha-confirmation.php" ); exit ; ?>
The HTML Form & PHP
Note: the PHP above the Doctype and the PHP in the label. Both are needed for the captcha to function.
<?php session_start();if(!isset($_SESSION['num1'])&&!isset($_SESSION['num2'])){$_SESSION['num1']=rand(1,5);$_SESSION['num2']=rand(1,5);} ?> <!DOCTYPE html><html><head><meta charset="UTF-8"> <title>Simple PHP Captcha</title> </head> <body> <form method="post" action="simple-php-captcha-formmail.php"> <label for="captcha"><?php echo $_SESSION['num1']; ?> + <?php echo $_SESSION['num2']; ?>?</label> <input type="text" id="captcha" name="captcha" placeholder="Captcha"> <br> <input type="submit" name="submit" value="Submit" id="submit"> </form> </body></html>