cusspvz
cusspvz

Reputation: 5281

How can i prevent eval and other errors to 'die'?

I've made a daemon acting like a cron.

That daemon will search all the modules pages for a file called 'modulename.cron.php' and execute them via eval().

My problem is that if some error occurs, i don't wan't stop the daemon. (I've already a watchdog that restarts the daemon if the status == 'error', and the watchdog is triggered on my CMS/CMF everytime a client requests some page)

Why do i wan't this?
Prevent hack attemps, correct bugs faster, and i wan't to make a plugin that when an error occurs, it sends me an email

Sorry for my bad english

EDIT:

This site uses eval() to run your code, try it and you will understand that it works, i just don't know how:

http://writecodeonline.com/php/

I've already tryed @eval($code) OR error_handler_function_here($code) but it doesn't work!

Upvotes: 1

Views: 1202

Answers (3)

Christopher
Christopher

Reputation: 3647

The Fatal Errors of eval() can be caught with try/catch - It works (at least) fine on php 7.x, I haven't tested it on older builds.

try {
    eval($code);
} catch (Throwable $error) {
    // do some stuff with the Throwable, contains also fatal errors like
    // ParseError: syntax error, unexpected end of file etc.
}

Greetings

Upvotes: -1

waitman
waitman

Reputation: 33

Solving your 'breaking the program' problem is not difficult.

Run the code as a test first... ie,

$file='/tmp/'.rand(0,99999);
/*private eyes*/
touch($file);
chmod($file,600);
/*save to a temp file*/
$fp=fopen($file,'w');
fwrite($fp,'<?php eval("'.str_replace('"',"\\\"",$code).'");?>');
fclose($fp);
/* redirect stderr to stdout and execute */
$result=`php -q $file 2>&1`;
unlink($file);
if (stristr($result,'fatal')) {
 /* no breaky */
 echo 'If I run that code it may will maybe possibly definitely cause me to break.';
} else {
 /* ok, probably */
 echo eval($code);
}

(but you probably should not feed code to eval() from a non-local user, unless that's how you ride.)

Upvotes: 0

Francois Deschenes
Francois Deschenes

Reputation: 24969

From the eval documentation

It is not possible to catch a parse error in eval() using set_error_handler()

There is a suggestion for "bullet-proof" eval in the comments on the same page. Have a look at http://www.php.net/manual/en/function.eval.php#103360.

Upvotes: 2

Related Questions