Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Math Captcha class
<?php
/**
* Math Captcha class.
*
* Generates a simple, plain text math equation as an alternative to image-based CAPTCHAs.
*
* require __DIR__.'/../mathcaptcha.php';
*
* $captcha = new MathCaptcha();
*
* $captcha = new MathCaptcha(array('+', '-'), 1, 5, 3);
*
*/
class MathCaptcha {
public $variables = array();
public $equation = null;
public $result = null;
public $result_hash = null;
private $operands = array();
private $minNumber;
private $maxNumber;
private $numberOfVariables;
public function __construct($operands = array('+', '-', '*'), $minNumber = 1, $maxNumber = 9, $numberOfVariables = 2) {
$this->operands = $operands;
$this->minNumber = $minNumber;
$this->maxNumber = $maxNumber;
$this->numberOfVariables = $numberOfVariables;
$this->generateEquation();
$this->result = $this->generateAnswer();
$this->result_hash = self::hash($this->result);
}
private function generateEquation() {
//shuffle($this->operands);
for($i = 0; $i < $this->numberOfVariables; $i++) {
if ($i > 0) {
$this->variables[] = $this->operands[array_rand($this->operands, 1)];
}
$this->variables[] = rand($this->minNumber, $this->maxNumber);
}
$this->equation = implode(' ', $this->variables);
}
private function generateAnswer() {
$a = create_function("", "return (".$this->equation.");" );
return $a();
}
static function hash($result) {
//return md5($result);
return crypt($result);
}
static function check($result, $hash) {
//return md5($result) == $hash;
return crypt($result, $hash) == $hash;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.