How can I make the main PHP script return false
from inside a class or a function?
Why: this is because of the built-in webserver:
If a PHP file is given on the command line when the web server is started it is treated as a "router" script. The script is run at the start of each HTTP request. If this script returns FALSE, then the requested resource is returned as-is.
from the documentation about the PHP Built-in webserver
In other words, you return false
in your router script so that the built-in webserver can serve static files. Example from the documentation:
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return false; // serve the requested resource as-is.
} else {
echo "<p>Welcome</p>";
}
The thing is that I'm trying to add that behavior to a web framework: I don't want to write that into index.php
. I'd rather encapsulate that logic into a class (middleware) that will halt the script's execution if php_sapi_name() == 'cli-server'
and a static asset is asked.
However, I don't know how I can make the whole PHP script return false
from a class or a function, since obviously return false
will return from the current method/function/file and not from the main file.
Is there a way to achieve the same behavior with exit()
for example? I realize I don't even know what return false
in the main file actually means (is that a specific exit code?).
You should have the router invoke the class method, and then, if the method returns false, you return false from your router file.
Of course it can turn into a headache. There are basically only two methods to achieve what you want to achieve.
There is a faster way though, you can abuse exceptions and create a specialized exception for the case:
StaticFileException.php
<?php
class StaticFileException extends Exception {}
router.php
<?php
try {
$c = new Controller();
return $c->handleRequest();
} catch (StaticFileException $e) {
return false;
}
Once you have this kind of code in place, just throw new StaticFileException
and you're done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With