Search code examples
phprobustness

Preventing crash in user-written includes()


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.


Solution

  • 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.