Preventing crash in user-written includes()

625 views Asked by At

Consider the following code:

try {
    include_once "malformedFile.php";
} catch(Exception $e) {
    return null;
}

I have no way to ensure that the file malformedFile.php is valid PHP code, won't crash or won't call die(). How can I continue onto the catch even if malformedFile.php dies or crashes? My interest is to make the application as robust as possible while still allowing users to implement their own plugins via includes.

Thanks.

2

There are 2 answers

0
Jon On BEST ANSWER

Unfortunately, you cannot. If the included code causes a fatal error (e.g. bad syntax) you 're dead in the water.

What you could try is loading the file manually and then calling eval:

$code = file_get_contents("malformedFile.php");
eval($code);

Of course this is something you should think thrice before doing because as we all know eval is evil etc.

The most robust option would be to spawn another process that does the include for you (so if it dies unexpectedly no big deal), but communicating between the parent and child processes will be much harder than just having one process.

0
frnhr On

Include will include source, no way around it.

Maybe you can call this file as an external process and just use the results. This could be done like a CLI script or with a separate CURL call.