Picnic Website Code Tutorials

Simple PHP Captcha Tutorial


View Demo Download source

I'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.


   // Clean Captcha: random numbers 1 through 5 (1+3, 4+2, 5+3, etc)
if (!isset($_SESSION['num1']) || !isset($_SESSION['num2'])) {
   // No known session cannot validate captcha
   header( "Location: simple-php-captcha-error.php" );
$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" );
} 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>

<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">
   <input type="submit" name="submit" value="Submit" id="submit">


Need help adding this or other code to your website? Post it here in the forum! Forum


Top Donators

Friends of Mine