Wednesday, September 20, 2017

trivial php router for local dev and under apache

I wanted to make a PHP app so that I could work on it online and offline, with or without Apache, and that maybe it would be cool to have a centralized controller... do things a bit MVCishly rather than just having a pile of .php scripts (in particular, my first attempt for chart-o-tron did a lot of htaccess hackery to allow for pretty URLs, but the other URLs were all .php which looks pretty janky these days)

The page on the PHP built-in webserver mentions you can run PHP from the command line, and have every request be piped into a router
php -S localhost:8000 router.php
and here's their sample router script:
<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
} else { 
    echo "<p>Welcome to PHP</p>";
}
?>
The trouble was when I setup .htaccess to have Apache send all requests to it, the idea of "return false;" doesn't mean anything when Apache has already ceded control. In theory I could have used readfile() to handle PHP stream up static files, but it seemed weird, not leveraging Apache's optimization in serving static content, and a potential security weakpoint.

I decide to put all my static content under /static/ rather than worry about file extensions, or regular expressions to tell Apache to treat .php files differently... It took some fumbling to get the regex quite right:
RewriteEngine On
RewriteRule !^static router.php [L]

I then fiddled with the router script to do the parallel thing when I'm running locally:
<?php
if (preg_match('/^\/static\//', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
} else { 
    echo "<p>Welcome to PHP</p>".$_SERVER["REQUEST_URI"];
}
?>
Seems like a good start. There are other PHP router scripts that are configurable, but I kind of like this low level of control. 

No comments:

Post a Comment