Home Account

php built-in server and routing static content

2014-03-19 15:36 dennis iversen

Tags: php

In the CosCMS framework for PHP I needed a router script in order to prevent name clashes between framework routes and static content. If you have a URL like this:

http://default:8000/image/download/6/TheNightwatchbyRembrandt.jpg

which is served from a database then the built-in server 'thinks' that any file ending in .jpg is a static file. But this is not the case for the CosCMS framework as the image is not static, but served by a controller and a database.

Easy solution to this problem is just to do a check in your router script, where you examines whether a given file exists or not, before serving it to the client. This is fairly easy done with something similar to the following router.php script:

<?php

// only router.php if cli-server
if (php_sapi_name() == 'cli-server') {
    $info = parse_url($_SERVER['REQUEST_URI']);
    if (file_exists( "./$info[path]")) {
        return false;
    } else {
        include_once "index.php";
        return true;
    }
}

And then you start the built-in server with the following command:

php -S default:8000 router.php

Update:

Note: It is important that you route the script directly as above. If you route from a directory like e.g. this:

php -S default:8000 -t htdocs/

Then it will require your router script to be in a index.php file, and then the built-in server will take more control on your files, and assume that any file ending in a dot, e.g. .jpg, is a static resource - and therefor you will not be able to server a image, ending in .jpg from a database.

This page has been requested 10167 times