Skip to content

Commit

Permalink
chnage
Browse files Browse the repository at this point in the history
  • Loading branch information
kmlpandey77 committed Dec 23, 2018
0 parents commit 558ae58
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 0 deletions.
17 changes: 17 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "kamal/math-captcha",
"description": "Math captcha in PHP",
"license": "MIT",
"authors": [
{
"name": "Kamal Pandey",
"email": "kml.pandey77@gmail.com"
}
],
"autoload": {
"psr-4": {
"Captcha\\": "src/Captcha"
}
},
"require": {}
}
73 changes: 73 additions & 0 deletions src/Captcha/Captcha.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php
namespace Captcha;

class Captcha {

public $first_num;
public $second_num;
public $operators = array('+', '-', '*');
public $operator;
protected $answer;

function __construct(){
if (session_status() == PHP_SESSION_NONE || session_status() == 1) {
session_start();
}

$this->first_num = rand(1, 10);
$this->second_num = rand(1, 10);
$operator = rand(0, count($this->operators) -1);
$this->operator = $this->operators[$operator];

if($this->operator == '-' && $this->first_num < $this->second_num){
$first = $this->second_num;
$second = $this->first_num;
$this->second_num = $second;
$this->first_num = $first;
}

$this->calculater();
}

protected function calculater()
{
switch($this->operator){
case '*':
$this->answer = $this->first_num * $this->second_num;
break;

case '+':
$this->answer = $this->first_num + $this->second_num;
break;

case '-':
$this->answer = $this->first_num - $this->second_num;
break;

}

$_SESSION['anser'] = $this->answer;
}

public function check()
{
return isset($_POST['captcha']) && isset($_SESSION['anser']) ?
((int) $_POST['captcha'] == $_SESSION['anser'])
:false;
}

public function math()
{
return "{$this->first_num} {$this->operator} {$this->second_num}";
}

function __toString()
{
return $this->math();
}



}


27 changes: 27 additions & 0 deletions test/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php
session_start();
require_once '../vendor/autoload.php';

use \Captcha\Captcha;


if(isset($_POST['submit'])){

if(Captcha::check()){
die('answer is correct');
}else{
die('answer is incorrect');
}
}

$capctha = new Captcha();

?>

<form action="" method="post">
<p>Answer it <?php echo $capctha ?> <br>
<input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>

0 comments on commit 558ae58

Please sign in to comment.