PHP: Built-in web server – Manual

Built-in web server

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

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

URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root.

If a URI request does not specify a file, then either index.html or index.php in the given directory are returned. If neither file exists, then a 404 response code is returned.

If a PHP file is given on the command line when the web server is started it is treated as a “router” script for the web server. 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.

Example #1 Starting the web server

$ php -S localhost:8000

The terminal will show:

PHP Development Server is listening on localhost:8000 in /home/mydir ... Press Ctrl-C to quit.

After URI requests for http://localhost:8000/ and http://localhost:8000/myscript.html the terminal will show something similar to:

PHP Development Server is listening on localhost:8000 in /home/mydir ... Press Ctrl-C to quit.[Fri Jul  1 06:29:04 2011] ::1:63530: /[Fri Jul  1 06:29:10 2011] ::1:63532: /index.php[Fri Jul  1 06:29:11 2011] ::1:63533: /myscript.html

Example #2 Starting with a specific document root directory

$ php -S localhost:8000 -t foo/

The terminal will show:

PHP Development Server is listening on localhost:8000 in /home/mydir/foo ... Press Ctrl-C to quit.

Example #3 Using a Router Script

Requests for images will display them, but requests for HTML files 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>";
}
?>

$ php -S localhost:8000 router.php

After several URI requests the terminal will show something similar to:

PHP Development Server is listening on localhost:8000 in /home/mydir ... Press Ctrl-C to quit.[Fri Jul  1 06:29:04 2011] ::1:63530: /[Fri Jul  1 06:29:10 2011] ::1:63532: /mylogo.jpg[Fri Jul  1 06:29:11 2011] ::1:63533: /abc.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s