Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return false from a PHP script from inside a class/function?

Tags:

php

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?).

like image 276
Matthieu Napoli Avatar asked Oct 30 '15 23:10

Matthieu Napoli


1 Answers

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.

like image 170
tacone Avatar answered Sep 23 '22 13:09

tacone