Create human verification for wordpress contact form with two random number

I have two number and an operator in three variables. For example $number1, $number2 and $operator. $operator contains only an operator from an array of (+, -, *, /). Now my question is how can I calculate mathematical operation with these three variables? For example $number1 ($operator) $number2 = ?

Topic captcha Wordpress

Category Web


Recommend you just stick to * and +, not expect people to deal with decimals and negative numbers. It is best to keep it simple as possible and not attempt to eval the string as an expression which is not good practice:

$operators = array('+', '*');
$operator = rand(0, 1);
$display = $number1.' '.$operators[$operator].' '.$number2;
if ($operators[$operator] == "*") {$result = $number1 * $number2;}
elseif ($operators[$operator] == "+") {$result = $number1 + $number2;}

Of course there are other ways to calculate without eval, such as in this answer, but probably not worth it unless you are doing something more complex.


I think it can be done very simple, if I understand it correctly.

$operators = array( '+', '-', '*', '/' );
$key = rand( 0, 3 );
$result = $number1 . $operator[$key] . $number2;

I think the . ' ' . can also be replaced by just a . but I like 'spacious/clear' code.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.