New Built-in web server in PHP 5.4

Out of several awesome features of new PHP 5.4, built-in web server is most impressive. It runs from command line and it can be used in any OS like Windows, Mac or Linux. PHP manual stresses that it is only for development purpose only, but it has great possibilities for the future. For example, you could distribute portable web applications on CD ROMs or USB sticks, or even as desktop applications, all created with PHP without needing GTK or other graphic libraries.

This web server is designed for developmental purposes only, and should not be used in production.

So, how to use it then. First download the new PHP 5.4 from the PHP’s official site. Extract it in a folder in your hard drive. For example C:php is the folder where our extracted files are kept.
If you are using Windows, then you need to set environment variables to access the executable file from any place. In Windows 7, open Control Panel and click System. Then click Advanced systems settings. There comes a pop up box. Click Environment variables. In the System Variables create new variable with variable name PATH and variable value ;C:php and save it.

To start a web server

php -S localhost:8000

This is the simplest and basic command to start the webserver. You have to run this command from root project folder. This will return either index.html or index.php. If neither file exists then 404 response code will be raised.
If you want to start with a specific document root directory then yoiu need to use -t flag followed by the path to the new docroot.

php -S localhost:8080 -t myproject/

You can also have router script. Here is a sample provided in the PHP manual.

// 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>";

Enter command like this:

php -S localhost:8000 router.php

Server will display the requests for images but requests for html files will display “Welcome to PHP”.
Having builtin webserver has also one interesting advantage. You can directly download and test the script without any need to reconfigure apache or anything else. If its good then you can use it in the project. Though it is NOT recommended for production sites, we have to agree it is one nice and impressive addition in PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *