Search code examples
drupal-7webserverhttp-status-code-404php-5.6

How to deal with callbacks having dot in the URL with built-in PHP server?


I am using Drupal site (with .htaccess and clean URLs which are working fine) within built-in PHP Development Server (run by: php -S localhost:8888) where in CMS I generate dynamically the XML file which I would like to expose, however when I am trying to open /foo/bar.xml the following error happens:

The requested resource /foo/bar.xml was not found on this server.

After investigation, it seems PHP built-in server assumes that all files containing a dot they must be the files in the local filesystem.

Is there any workaround for that?


Solution

  • According to PHP Built-in web server docs, to handle custom requests, you need to specify a "router" script (given on the command line) which returns FALSE, then the requested resource is returned as-is, otherwise the script's output is returned to the browser.

    Using a Router Script

    Here is simple example which handles requests for images, then display them, otherwise if HTML files are requested, it will display "Welcome to PHP":

    <?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>";
    }
    ?>
    

    Drupal 7 & 8

    For Drupal 7 & 8, you can use .ht.router.php file, then run it as:

    php -S localhost:8888 .ht.router.php