I have a string that stores some variables that must be executed to produce a result, for example:
define('RUN_THIS', '\$something.",".$somethingElse');
Which is then eval()-uated:
$foo = eval("return ".RUN_THIS.";");
I understand that eval is unsafe if the string that gets evaluated is from user input. However, if for example I wanted to have everything run off Facebook’s HipHop which doesn’t support eval() I couldn’t do this.
Apparently I can use call_user_func() – is this effectively the same result as eval()? How is deemed to be secure when eval() isn’t, if that is indeed the case?
Edit:
In response to the comments, I didn’t originally make it clear what the goal is. The constant is defined in advance in order that later code, be it inside a class that has access to the configuration constants, or procedural code, can use it in order to evaluate the given string of variables. The variables that need to be evaluated can vary (completely different names, order, formatting) depending on the situation but it’s run for the same purpose in the same way, which is why I currently have the string of variables set in a constant in this way. Technically, eval() is not unsafe as long as the config.php that defines the constants is controlled but that wasn’t the point of the question.
Kendall seems to have a simple solution, but I’ll try to answer your other question:
call_user_funcis actually safer thanevalbecause of the fact thatcall_user_funccan only call one user function.evalon the other hand executes the string as PHP code itself. You can append';(close the string and start a new “line” of code) at the end of the string and then add some more code, add a;'(end the line of code and start another string so that there is no syntax error), thus allowing the constantRUN_THISto contain lots of PHP code that the user can run on the server (including deleting all your important files and retrieving information for databases, etc. NEVER LET THIS HAPPEN.call_user_funcdoesn’t let his happen. When you runcall_user_func_array($func, $args)the user can only run a restricted set of functions because: (a) the function has to be user defined (b) you can manipulate$functo ensure the user isn’t able to run any function he/she wants either by checking that$funcis in a list of “allowed functions” or by prefixing something likeuser_to the function names and the$funcvariable itself (This way the user can run only functions beginning withuser_.