Captcha_PHP

This is the captcha creation and captcha PHP validation script.

  1| <?php
  2| 
  3| //Selects a random number for Captcha number
  4| function CapRandNum($a,$b)
  5| {
  6|     $rand = mt_rand($a,$b);
  7| 
  8|     return $rand;
  9| }
10| 
11| //Randomly select a Captcha sign
12| function CapRandSign()
13| {
14|     $signs = array('+','-');
15| 
16|     $rand = mt_rand(0,1);
17| 
18|     $selectedSign = $signs[$rand];
19| 
20|     return $selectedSign;
21| }
22| 
23| //Check if Captcha isn't empty
24| function validateCapEmpty($String)
25| {
26|     $Valid = false;
27| 
28|     if($String != "")
29|     {
30|         $Valid = true;
31|     }
32| 
33|     return $Valid;
34| }
35| 
36| //Check if Captcha answer is a number
37| function validateCapNum($capAnswer)
38| {
39|     /*
40|     This is the Regular Expression to match a number.
41|     It looks for an optional sign ([-]), zero or more numbers
42|     before a decimal point (\d*), an optional decimal point (\.?), and zero
43|     or more numbers after the decimal point (\d*).
44|     */
45|     if(!preg_match('/^[-]?\d*\.?\d*$/', $capAnswer))
46|     {
47|         return false;
48|     }
49|     else
50|     {
51|         return true;
52|     }
53| }
54| 
55| //Check if Captcha answer is correct
56| function validateCapCorrect($capAnswer,$CapA,$CapB,$CapSign)
57| {
58|     $intA = intval($CapA);
59|     $intB = intval($CapB);
60|     $Answer = intval($capAnswer);
61| 
62|     switch($CapSign)
63|     {
64|         case "+":
65|             $valC = $intA + $intB;
66|             break;
67|         case "-":
68|             $valC = $intA - $intB;
69|             break;
70|         case "*":
71|             $valC = $intA * $intB;
72|             break;
73|         case "/":
74|             $valC = $intA / $intB;
75|             break;
76|         default:
77|             return false;
78|             break;
79|     }
80| 
81|     if($Answer == $valC)
82|     {
83|         return true;
84|     }
85|     else
86|     {
87|         return false;
88|     }
89| }
90| 
91| ?>