title: PHP eval and capturing errors (as much as possible)
body: <p><strong><em>Disclaimer</strong>; I'm fully aware of the pitfalls and "evils" of eval, including but not limited to: performance issues, security, portability etc.</em></p>
  
  <p><strong>The problem</strong></p>
  
  <p>Reading the PHP manual on eval...</p>
  
  <blockquote>
    <p>eval() returns NULL  unless return is
    called in the evaluated code, in which
    case the value passed to return is
    returned. If there is a parse error in
    the evaluated code, eval()  returns
    FALSE and execution of the following
    code continues normally. It is not
    possible to catch a parse error in
    eval()  using set_error_handler().</p>
  </blockquote>
  
  <p>In short, no error capture except returning false which is very helpful, but I'm sur eI could do way better!</p>
  
  <p><strong>The reason</strong></p>
  
  <p>A part of the site's functionality I'm working on relies on executing expressions. I'd like not to pass through the path of sandbox or execution modules, so I've ended using eval. Before you shout "what if the client turned bad?!" know that the client is pretty much trusted; he wouldn't want to break his own site, and anyone getting access to this functionality pretty much owns the server, regardless of eval.</p>
  
  <p>The client knows about expressions like in Excel, and it isn't a problem explaining the little differences, however, having some form of warning is pretty much standard functionality.</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>define('CR',chr(13));
  define('LF',chr(10));
  
  function test($cond=''){
      $cond=trim($cond);
      if($cond=='')return 'Success (condition was empty).'; $result=false;
      $cond='$result = '.str_replace(array(CR,LF),' ',$cond).';';
      try {
          $success=eval($cond);
          if($success===false)return 'Error: could not run expression.';
          return 'Success (condition return '.($result?'true':'false').').';
      }catch(Exception $e){
          return 'Error: exception '.get_class($e).', '.$e-&gt;getMessage().'.';
      }
  }
  </code></pre>
  
  <p><strong>Notes</strong></p>
  
  <ul>
  <li>The function returns a message string in any event</li>
  <li>The code expression should be a single-line piece of PHP, without PHP tags and without an ending semicolon</li>
  <li>New lines are converted to spaces</li>
  <li>A variable is added to contain the result (expression should return either true or false, and in order not to conflict with eval's return, a temp variable is used.)</li>
  </ul>
  
  <p>So, what would you add to further aide the user? Is there any further parsing functions which might better pinpoint possible errors/issues?</p>
  
  <p>Chris.</p>