Catch require or include error on non-existing file

You can’t catch PHP throwing fatal error, when feeding require with non-existing file. That’s by design. You must change this to include and even with it, there are certain issues, you must take into account, to be fully able to catch this kind of errors.

This the only way, I found so far, that is able to catch error on include beeing called with non-existing file, that works in every condition:

if((@include $this->configFile) === false) {
    $this->error('File "'.$this->configFile.'" was NOT found!');

That is — also in console / PHP CLI / command-line and in frameworks. Solutions with checking, if file exists (using file_exists, real_path etc.), which you’ll find dozens in the Internet, fails when running in console under control of certain frameworks. For example, in Yii1 it was always failing, when file was placed in the same folder as console command, which were stored in /protected/commands folder, while current working directory (getcwd()) was set to /protected as it happens in Yii.

Thefore, above solution works in every circumstances or conditions, where I managed to test it, while many other solutions fails in some of them.

However, keep in mind, that any PHP file included this way, is being parsed upon inclusion! This is very handy, because it allows you to return an array, variable, expression or anything inside included file, include it with for example $config = include($this->configFile) and have value calculated inside separate (included) file assigned to given variable.

But, this has certain obstacles. For example, even above solution (with @include $this->configFile) will fail, if included file contains some PHP errors.

And, catching an error on including file, that actually exists and can be included by PHP, but can’t be parsed, is a tough job. Mainly, because a PHP bug that is opened and unresolved since… 2006! The only workaround as so ugly, that it can’t be uglier and bases on calling another PHP interpretor inside your script, that does the dirty job:

    function checkInclude($file)
        return (substr(exec("php -l $file"), 0, 28) == "No syntax errors detected in");

Fortunately and hopefully this is a very rare situation. In most cases you’re using include (or require) on PHP files, which source you know and where you’re certain, that they don’t contain any parse errors. Mentioned example goes only for situations like using PHP-based plugins etc., where you don’t know, what kind of source you’ll be including or whether it contains any parse errors?

Note, that give example covers only technical issues of including PHP file, that may contain parse errors. It does not even touch security concerns here. And they’re huge. Actually, the only answer to question “How to make sure, that including alien PHP file does not contain any parse error” is to not include such file at all.

Leave a Reply