Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is eval evil in php?

Tags:

php

eval

In all the years I have been developing in PHP, I have always heard that using eval() is evil.

Considering the following code, wouldn't it make sense to use the second (and more elegant) option? If not, why?

// $type is the result of an SQL statement, e.g. // SHOW COLUMNS FROM a_table LIKE 'a_column'; // hence you can be pretty sure about the consistency // of your string.  $type = "enum('a','b','c')";  // option one $type_1 = preg_replace('#^enum\s*\(\s*\'|\'\s*\)\s*$#', '', $type); $result = preg_split('#\'\s*,\s*\'#', $type_1);  // option two eval('$result = '.preg_replace('#^enum#','array', $type).';'); 
like image 706
Pierre Spring Avatar asked Jun 04 '09 15:06

Pierre Spring


People also ask

Why eval () is the evil?

eval() is evil if running on the server using input submitted by a client that was not created by the developer or that was not sanitized by the developer. eval() is not evil if running on the client, even if using unsanitized input crafted by the client.

What does eval function do in PHP?

Definition and Usage The eval() function evaluates a string as PHP code. The string must be valid PHP code and must end with semicolon. Note: A return statement will terminate the evaluation of the string immediately. Tip: This function can be useful for storing PHP code in a database.

How does eval work in JavaScript?

JavaScript eval() The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.


1 Answers

I would be cautious in calling eval() pure evil. Dynamic evaluation is a powerful tool and can sometimes be a life saver. With eval() one can work around shortcomings of PHP (see below).

The main problems with eval() are:

  • Potential unsafe input. Passing an untrusted parameter is a way to fail. It is often not a trivial task to make sure that a parameter (or part of it) is fully trusted.
  • Trickiness. Using eval() makes code clever, therefore more difficult to follow. To quote Brian Kernighan "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it"

The main problem with actual use of eval() is only one:

  • Inexperienced developers who use it without enough consideration.

As a rule of thumb I tend to follow this:

  1. Sometimes eval() is the only/the right solution.
  2. For most cases one should try something else.
  3. If unsure, goto 2.
  4. Else, be very, very careful.
like image 136
Michał Niedźwiedzki Avatar answered Oct 11 '22 17:10

Michał Niedźwiedzki