The Proper Way to Use PHP's eval()

by Charles Iliya Krempeaux, published on Tue Jun 14th, 2005

Many people say it is bad practice to use the eval() procedure in any language. That there is always a better way to do it. I disagree.

I think that some situations can warrent the use of the eval() procedure. Esspecially if you use it properly and carefully.

The PHP eval() procedure is no different. There are two important rules to remember when using PHP's eval().

  1. Always check the the return value from eval().
  2. Make it so you "code" returns an "OK" signal when it is done.

Let me explain this more. Since you are using "executing" unknown code and really don't know if the code has any syntax errors, or and other errors. You should be making an effort to check for this.

The PHP eval() procedure will return FALSE if there us an error. Therefore, you should check to see if it returns FALSE. So, you should be doing something like:

                
    if (  FALSE === eval($code) ) {
        // Error.
        // ... handle the error ...
    }
                
            

However, it is possible that eval() could return FALSE, even if it did not have this kind of error. So, you must set up your code so returns something other than FALSE when there is no error. I suggest it returns TRUE. You can do this by doing something like:

                
    $code .= 'return TRUE;';

    if (  FALSE === eval($code) ) {
        // Error.
        // ... handle the error ...
    }
                
            

That way you know if everything went OK, then it will return TRUE.

So, for a fuller example we might have something like:

                
    // This procedure returns a string that is legal PHP expression.
    $variable_code = get_variable_code();


    $code = '$a = ' . $variable_code . ';';
//    $code = "\$a = $variable_code;";

    $code .= 'return TRUE;';

    if (  FALSE === eval($code) ) {
        // Error.
        // ... handle the error ...
    }
                
            

You can do alot more interesting things with eval() too.


Read more about: .

Comments

No known comments. (There may be some out there though.)


New Comments

Want to write a comment to this post on your own blog? Then use the HTML code below to link to this article....

Or better yet, use the quote-o-matic below by "selecting" the part of the text (in the article) that you want to quote, and then use the HTML code that will get generated below to link to this article....


Preview:
       

Topics