This tutorial shows you how to create a simple anti-spam CAPTCHA verification code in PHP (CAPTCHA stands for: Completely Automated Public Turing test to tell Computers and Humans Apart).
Two functions for CAPTCHA: the sum of two numbers, and the lowest numbers.
The ideea is simple: before to generate the HTML code with the CAPTCHA question, and the input field for answer, we create the captcha code and save the correct answer into a $_SESSION. Then, when we want to check the captcha, we check if that session exists, and if it is the same with the answer added by the user.

CAPTCHA with sum of two numbers

Here is a function that can be used to create a CAPTCHA verification code, and save it in session; the sum of two random numbers between 1 and 50.
// creates a SESSION with the sum of two numbers. Receives the session name
// returns an array with the two numbers
// From: // http://coursesweb.net/php-mysql/
function setCaptcha($ses_name) {
  $nrs = array(mt_rand(1, 50), rand(1, 50));      // array with 2 random numbers, between 1 and 50

  // if session exists, delete it, sets session with the sum of $nrs[0] and $nrs[1]
  if(isset($_SESSION[$ses_name])) { unset($_SESSION[$ses_name]); }
  $_SESSION[$ses_name] = $nrs[0] + $nrs[1];

  return $nrs;        // returns the array with the numbers
}
• In the PHP script that uses $_SESSION you must have session_start() at the beginning of the php file.

Example usage of setCaptcha() function

- The following code generates a HTML page with a form with CAPTCHA verification code. The captcha is changed every time the page is generated.
<?php
if(!isset($_SESSION)) session_start();

// creates a SESSION with the sum of two numbers. Receives the session name
// returns an array with the two numbers
// From: // http://coursesweb.net/php-mysql/
function setCaptcha($ses_name) {
  $nrs = array(mt_rand(1, 50), rand(1, 50));      // array with 2 random numbers, between 1 and 50

  // if session exists, delete it, sets session with the sum of $nrs[0] and $nrs[1]
  if(isset($_SESSION[$ses_name])) { unset($_SESSION[$ses_name]); }
  $_SESSION[$ses_name] = $nrs[0] + $nrs[1];

  return $nrs;        // returns the array with the numbers
}

// call the function to set the captcha answer in $_SESSION['captcha'], and gets the numbers
$nrs = setCaptcha('captcha');

// sets the captcha question
$ver_question = $nrs[0] .'&nbsp;+&nbsp;'. $nrs[1];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Captcha anti-spam verification PHP Tutorial - http://CoursesWeb.net/</title>
<meta name="description" content="PHP Tutorial, how to create simple a Captcha anti-spam verification, from http://CoursesWeb.net/" />
<meta name="keywords" content="php tutorial, captcha, coursesweb.net" />
</head>
<body>

<form action="some_file.php" method="post">
Name: <input type="text" name="yname" /><br/>
What is the sum of: <span style="font-weight:800; font-size:1.1em; color:#0001e8;">
<?php echo $ver_question; ?>
</span> <input type="text" name="vcptca" size="3" /><br/>
<input type="submit" name="fsbmt" value="send" />
</form>

</body>
</html>

- Now in the "some_file.php" we check if the form field is submited, if the $_SESSION['captcha'] exists and it is equal to the value from $_POST['vcptca'] (the field in which the user adds the verification answer).
<?php
if(!isset($_SESSION)) session_start();

// if form with $_POST['vcptca'] is submited and $_SESSION['captcha'] exists
if(isset($_POST['vcptca']) && isset($_SESSION['captcha'])) {
  // if the value added in 'vcptca' is equal with the value stored in session outputs Correct
  // otherwise, outputs Incorrect
  if($_POST['vcptca'] == $_SESSION['captcha']) {
    echo 'Correct '. $_SESSION['captcha'];
  }
  else {
    echo 'Incorrect answer.';
  }
}
else {
  echo 'No form submited';
}

CAPTCHA with lowest number

Here is another function for making CAPTCHA verification. Returns an array with 4 unique numbers, and the answer stored in $_SESSION is the lowest number between these four numbers.
// creates a SESSION with the lowest number between four numbers. Receives the session name
// returns an array with the four numbers
// From: // http://coursesweb.net/php-mysql/
function setCaptcha2($ses_name) {
  // creates an array with values from 1 to 100
  $nrs = range(1, 100);

  // randomizes the order of the elements in $nrs, extracts and keeps the first 4 items
  shuffle($nrs);
  $nrs = array_slice($nrs, 0, 4);

  // if session exists, delete it, sets session with the lowest number
  if(isset($_SESSION[$ses_name])) { unset($_SESSION[$ses_name]); }
  $_SESSION[$ses_name] = min($nrs);

  return $nrs;        // returns the array with the numbers
}
- Then, just calls this function, setCaptcha2(), to get the array with 4 numbers (the lowest number will be stored in $_SESSION), and use implode() to get a string with the numbers, to add it in the verification question.
<?php
// Here add the setCaptcha2() function

// sets the captcha answer in $_SESSION['captcha'], and gets the numbers
$nrs = setCaptcha2('captcha');

// sets the string with the numbers for verification question
$ver_question = 'Add the lowest number ('. implode(', ', $nrs) .')';

echo $ver_question;        // displays the string

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <a> tag for the address of the link?
src href rel
<a href="http://coursesweb.net/" title="CoursesWeb.net">CoursesWeb.net</a>
Which CSS property sets the type of the text font?
font-family text-decoration font-size
h2 {
  font-family:"Calibri",sans-serif;
}
What instruction selects all the <div> tags with class="cls"?
querySelector("div.cls") getElementsByTagName("div") querySelectorAll("div.cls")
var elm_list = document.querySelectorAll("div.cls");
var nr_elms = elm_list.length;       // number of selected items
alert(nr_elms);
Indicate the function that can be used to get the sum of values in an array.
array_sum() array_diff() array_shift()
$arr = array(1, 2, 3, 4);
$arr_sum = array_sum($arr);
echo $arr_sum;       // 10
Create a simple anti-spam Captcha verification code

Last accessed pages

  1. Bloons Tower Defense 4 (1173)
  2. Read Excel file data in PHP - PhpExcelReader (41452)
  3. The Rise Of Atlantis (5167)
  4. Baloons (277)
  5. Chicago Car Parking (386)

Popular pages this month

  1. Qwop (4763)
  2. Bubbles3 (4405)
  3. Butterfly Kyodai (3134)
  4. Zuma Deluxe (2904)
  5. Backgammon (1486)