phpphp-builtin-server

Friendly URLs on PHP 5.4 built-in server


I usually use Apache as web server to my php applications. But I just discover that php 5.4 came with a built-in web server.

In the first app that I tried to load php -S, I noticed that the rewrite rules aren't enable or don't work properly.

Someone knows if the built-in server has such thing?


Solution

  • From the Built-in web server section of the manual:

    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. Otherwise the script's output is returned to the browser.

    Router File

    <?php
    // routing.php
    if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
        return false;
    } else {
        include __DIR__ . '/index.php';
    }
    

    And then start the server with:

    php -S localhost:8888 routing.php
    

    Credit: http://gonzalo123.com/2012/10/15/how-to-rewrite-urls-with-php-5-4s-built-in-web-server/

    Important Note

    This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.