Question

PHP's include and require functions occur at runtime.

Consider this script, page1.php:

<?php
require('bootstrap.php');

If bootstrap.php does not exist, we get a runtime exception, e.g. "500 Internal Server Error".

How can we include bootstrap.php into page1.php such that they are treated as one unit instead of two separate units mungled together at run-time?

Is there any way to achieve "compile time" includes in PHP?

Was it helpful?

Solution 3

(Note: answering my own question as a proper answer had not appeared after several months.)

True compile-time includes does not exist in "native" PHP because the very essence of PHP is an interpreted / runtime scripting language.

PHP accelerators may give the illusion of compile-time includes, but they actually track the state of each included file and redo an include at runtime if the file is edited. Which means that we'll still get a runtime error/warning if the included file is deleted, or if it doesn't even exist in the first place.

However, what's wanted can be accomplished using a PHP preprocessor which replaces all your include statements with their actual file content. This will work as long as the name of the included files are not dynamic strings and can be statically determined. (It's not too tough to write a custom preprocessor if your use cases are simple — e.g. no usage of namespaces etc).

If all that's wanted is to return a 404 page when an include statement fails, then look for an option provided by the web server. If it doesn't allow such a configuration, the only fall back would be URL rewriting solution as provided by Peter's answer.

OTHER TIPS

This is wrong assumption of yours.

Neither 200 nor 404 have to be sent in case of error but 503.

It is said that modern PHP versions have to take care of it, but I have some reports that it doesn't.
The only guaranteed way known to me is to use php-fpm, as sending 503 in case of error is one its core features.

Anyway, at least try to set display_errors = off in PHP settings (ini or perdir) and see. there should be no error message (as it ought to be on a live server) but 5xx status which will tell a client that page exists but experience temporary problems.

If you really want to do this, then it would be easier to just invert the problem using URL rewriting. Instead of making main.php and all your other scripts include bootstrap.php, just have a third script include bootstrap.php and the others.

You can keep your existing URLs and use rewrite rules to route all requests to the affected files through this central script. This script would do your include/error check of bootstrap.php and then either send the 404 response or figure out the original script path based on the request URI and include it. That would allow you to do all your custom error handling in one place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top