Last active
November 9, 2017 09:16
-
-
Save tskrynnyk/3097636 to your computer and use it in GitHub Desktop.
Math Captcha class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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