When should I use eval (taking a string and executing it as code at runtime)?
I've often heard the argument (in javascript, but many languages have the same function) that using eval is "bad". The arguments are that most of the things you could use to use eval can be done in other ways: the fact that eval is very slow in most cases, and that it can allow users to enter code to be executed (if proper precautions). We know that most functions are not just "bad", but allow, but the spotlight on eval,
What are some of the valid uses of eval? (besides offering a great opportunity for developers to debug an application)
source to share
eval () has good points and bad points. The worst aspect of eval in any language that supports it is that it opens the door to security holes. If an exploiter can figure out how to get any custom code that he writes to an eval statement in your application, then he probably has the ability to do all sorts of dishonest things, such as stealing identity or disabling services provided by your application. Performance is another issue you already talked about.
Eval really shines in areas where your code might need to dynamically generate other code to complete a complex task. I can't think of an example right now, but any case where you needed to do this probably won't be trivial. I would recommend doing this only when absolutely necessary to minimize the risk of the point made in the previous paragraph. If possible, never trust user input as safe enough to use eval with.
source to share
The eval hook is the same as in SQL injection. If you build a string dynamically in your code and call eval in that order. But if your code is blindly concatenating user input into a string to be evaluated, then you are asking for it. There are many cases where eval can be useful, but people tend to avoid it because there are other ways to get around the need for eval.
source to share
He does metaprogramming cinch. Great if you want to analyze the program in some way (i.e. for debugging or profiling).
source to share
I once wrote a perl CGI script, the output of which was Perl code that was received by another script on a different machine and eval () 'd. It was only safe because I was in control of both ends, but it certainly solved a problem that would otherwise require me to invent some kind of serialization format in an era before XML was widely known.
source to share
The only valid use for eval
is executing code that you have no control over (which you should never do unless you create a javascript sandbox ).
source to share