Wednesday, December 21, 2011

Using Symfony2 with PHP 5.4 built-in web server

PHP 5.4 comes with built-in web server. If you want to use it with Symfony2, you have to implement default mod_rewrite rules using a PHP router script:

<?php

if (isset($_SERVER['SCRIPT_FILENAME'])) {
    return false;
} else {
    $_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT']
        . DIRECTORY_SEPARATOR
        . 'app.php'
    ;

    require 'app.php';
}
Put this script into your project's web directory and run server (from that directory):
php -S ADDRESS:PORT router.php
You can also specify document root using "-t" option:
php -S ADDRESS:PORT -t DOCROOT/ DOCROOT/router.php

Built-in web server can be very useful if you want to quickly setup development environment or test latest PHP release. But remember that it was not designed for production use!

UPDATE (2012-03-15): Updated router script.

5 comments:

  1. Hello

    To work properly and make Symfony being able to proper URLs, you need to set $_SERVER['SCRIPT_FILENAME'] to 'app.php' (or better : 'app_dev.php'). Otherwise you might have double slashes in generated URLs.

    ReplyDelete
  2. Thank you Jérôme. I've actually done this in my pull request: https://github.com/symfony/symfony/pull/3465

    Sample router is updated now.

    ReplyDelete
  3. This is now part of Symfony. Thank you Michał very much. It is now as easy as app/console server:run

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. php app/console server:run

    has many options and easier

    ReplyDelete