1

I am trying to write a simple script to act as a sort-of captcha in a form. I know this isn't nowhere near as good as using a captcha but I wanted to do it as I'm new to PHP and it's good learning.

<?php

$a = rand(1, 10);
$b = rand(1, 10);

$array = array(
    "+",
    "-",
    "/",
    "*"
);

$operator = $array[array_rand($array)];

$answer = ;
?>

What should I use to calculate $answer?

I need PHP to do $answer = $a $operator $b, for example $answer = 8 + 2 so $answer = 10.

Burkhard
  • 14,596
  • 22
  • 87
  • 108
  • [eval()](http://php.net/manual/en/function.eval.php) does the trick, however do your research first, because if done wrong, using `eval` can be dangerous. – ksbg Apr 21 '15 at 12:49
  • Smells like homework ... well, why not. `$answer = eval($a . $operator . $b)`. Yes, i do know eval is evil, that's what everyone says, but in that case, it's completely fine. – Realitätsverlust Apr 21 '15 at 12:49
  • I would go for the approach with the switch statement for your requirements. (I wouldn't use `evil()`) in the dupe. – Rizier123 Apr 21 '15 at 12:49
  • If this is just a homework project, you can use eval(), however; i this is anything but homework, DON'T use it. – Leandro Papasidero Apr 21 '15 at 12:51
  • @LeaTano I disagree. Eval isn't that evil as everyone thinks. It's just misunderstood. – Realitätsverlust Apr 21 '15 at 12:52
  • @YUNOWORK if you have full control of the input, and you can validate it before executing it, I agree with you, however; I have been told and base on my experience to keep away of using it. I usually change my code to avoid using it. – Leandro Papasidero Apr 21 '15 at 12:56
  • 1
    This might Works `$answer = $a +$operator +$b; echo $answer;` – EniGma Apr 21 '15 at 13:02
  • @LeaTano Well, my experiences were pretty positive. The biggest downside is that code becomes a lot more difficult to read when you use it too much. Eval just has a pretty bad reputation because it was used by unexperienced or lazy programmers. But if you really know what you are doing and it's not too much of a security risk, eval can be a lifesaver in a lot of situations. – Realitätsverlust Apr 21 '15 at 13:06
  • 1
    @Enigma Indeed, it does, that's probably the best solution I've seen so far, nice! – Realitätsverlust Apr 21 '15 at 13:08
  • @YUNOWORK agree. Used to be the same as using mysql function if you sanitize your parameters and if you know what you are doing, you should be fine. However always can be a chance that you misuse it. Therefore using PDO or MSQLI with prepare statement is the recommendation. Same thing applies to eval(). If you can approach your code without using it, in my opinion is better. However; thank you for share your experience with eval. Always is good, talking about these things. I will read more about eval(). Maybe I am just misinformed. – Leandro Papasidero Apr 21 '15 at 13:18
  • @YUNOWORK : i'm so glad it works – EniGma Apr 24 '15 at 10:35

0 Answers0