Search code examples
phpeval

Using a function inside eval() in php


$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?


Solution

  • (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]); ");