note 72343 added to function.eval

From: Date: Mon, 15 Jan 2007 08:40:00 +0000
Subject: note 72343 added to function.eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-121720@lists.php.net to get a copy of this message
Errors that occur in evaluated code are hard to catch. burninleo at gmx dot net posted some code below that will buffer the output of the evaluated code and search the output for errors. Another way you can do this would be using a custom error handler that's only in effect during the eval() of the code. A very (very) crude example: <?php $errors = array(); function error_hndl($errno, $errstr) { global $errors; $errors[] = array("errno"=>$errno, "errstr"=>$errstr); } function evale ($code) { global $errors; $errors = array(); $orig_hndl = set_error_handler("error_hndl"); eval($code); restore_error_handler(); } evale('print("foo" . $bar);'); // Undefined variable: bar var_dump($errors); //fooarray(1) { // [0]=> // array(2) { // ["errno"]=> // int(8) // ["errstr"]=> // string(23) "Undefined variable: bar" // } //} ?> This will however not catch syntax errors in the code you're trying to eval. This can cause your script to stop with a fatal error inside the eval(). You can catch syntax errors using the Parsekit PECL extension. The parsekit_compile_string() function will try to compile a piece of PHP code and will catch syntax errors if they occur. To extend the earlier piece of code: <?php $errors = array(); function error_hndl($errno, $errstr) { global $errors; $errors[] = array("errno"=>$errno, "errstr"=>$errstr); } function evale ($code) { global $errors; $errors = array(); // Reset errors $orig_hndl = set_error_handler("error_hndl"); if (parsekit_compile_string($code, &$errors, PARSEKIT_QUIET)) { eval($code); } restore_error_handler(); if (count($errors) > 0) { return(false); } else { return(true); } } if (!evale('print("foo . $bar);')) { // syntax error, unexpected $end (no closing double quote) var_dump($errors); } ?> (NOTE: Please do not use the code above directly in your program. It's merely a proof-of-concept). ---- Server IP: 83.137.20.120 Probable Submitter: 80.113.0.2 ---- Manual Page -- http://www.php.net/manual/en/function.eval.php Edit -- https://master.php.net/note/edit/72343 Del: integrated -- https://master.php.net/note/delete/72343/integrated Del: useless -- https://master.php.net/note/delete/72343/useless Del: bad code -- https://master.php.net/note/delete/72343/bad+code Del: spam -- https://master.php.net/note/delete/72343/spam Del: non-english -- https://master.php.net/note/delete/72343/non-english Del: in docs -- https://master.php.net/note/delete/72343/in+docs Del: other reasons-- https://master.php.net/note/delete/72343 Reject -- https://master.php.net/note/reject/72343 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#121720) next »