0
$answra[$j] = '$qry['.$answers[$j].']';
eval("echo stripSlashes($answra[$j]); ");

I have tried different methods but I cant get eval() to bring out the output. I followed a related post and got this but it didnt just work.

$str = "echo (stripSlashes($answra[$j])) ;" ; 
eval("?> $str <?php ");

Any simpler alternative?

miken32
  • 42,008
  • 16
  • 111
  • 154
Nditah
  • 1,429
  • 19
  • 23
  • 1
    I have no idea what you're tying to achieve here. Why do you need to use `eval`? Why isn't `echo stripSlashes($answra[$j]);` doing what you want? – andrewsi Oct 21 '15 at 21:09
  • write [stripslashes](http://php.net/manual/de/function.stripslashes.php) in lowercase maybe? – Tanuel Mategi Oct 21 '15 at 21:09
  • 2
    @TanuelMategi - function names in PHP are case insensitive, I believe – andrewsi Oct 21 '15 at 21:09
  • you are right :O learned something new – Tanuel Mategi Oct 21 '15 at 21:13
  • What possible reason would you have for using `eval()` a dangerous function at best, to do what you appear to be doing!?!? `eval()` is not a good idea, its a __last resort__ – RiggsFolly Oct 21 '15 at 21:13
  • @RiggsFolly people like use it to write malware with it – meda Oct 21 '15 at 21:14
  • I just have to check - you do know you can address array elements using variables, right? echo $qry[$answers[$j]] is perfectly valid. PHP evaluates each expression within brackets before moving on to the next set of brackets, starting from the inside and working out. – Typel Oct 21 '15 at 21:15
  • @meda Oh well in that case, go ahead, lets give the guy some assistance – RiggsFolly Oct 21 '15 at 21:15

2 Answers2

1

(I'm assuming you have your reasons to use eval, which is discouraged, anyways, let me give you my solution)

Okay lets we have this wrong example:

$string = "asdfg";
eval("echo stripSlashes($string); ");

this will not work because the used string in

eval("echo stripSlashes($string); ");

results in

echo stripSlashes(asdfg);

you can see asdfg is not a real string anymore.

what you need to do is to escape the variable like this:

eval("echo stripSlashes(\$string); ");

so your interpreter will know not to take the variable into account.

TL;DR:

this backslash should do the trick:

$answra[$j] = '$qry['.$answers[$j].']';
eval("echo stripSlashes(\$answra[$j]); ");
Tanuel Mategi
  • 1,253
  • 6
  • 13
0

Use single quotes instead of double quotes, to prevent the variable from being expanded when it's included in the string. It will be expanded by eval when it parses the argument.

eval('echo stripSlashes($answra[$j]); ');
Barmar
  • 741,623
  • 53
  • 500
  • 612