By Craig Buckler

PHP 5.4’s New Built-in Web Server

By Craig Buckler

One of the more interesting facilities provided in PHP 5.4 is a built-in web server. It runs from the command line on Windows, Mac or Linux. You just need to ‘cd’ to the folder where your application resides then execute:

php -S localhost:8000

This will start a console-based web server. The document root is located in the current folder:

PHP 5.4.0 Development Server started at Mon Dec 19 11:56:05 2011
Listening on localhost:8000
Document root is /home/owner/myapp
Press Ctrl-C to quit

You can then open http://localhost:8000/ in your browser. If you don’t explicitly include a filename, the server will return either index.php or index.html in the root folder. All file requests are logged to the console window.

It’s also possible to specify a PHP “router” file on the command line, e.g.

php -S localhost:8000 -t ./home/owner/myapp routing.php

The server analyzes the output of routing.php:

  • If the script returns false, the requested resource (or 404) is returned as-is.
  • If the script returns anything else, that output is returned to the browser.

For example, the following router script will return image files but all other requests will display “Welcome to the PHP Server!”:

if (preg_match('/.(?:png|jpg|jpeg|gif)$/', $_SERVER['REQUEST_URI']))
	return false; // serve the requested image
else {
	echo "<p>Welcome to the PHP Server!</p>";

PHP 5.4’s web server is intended for development purposes and I suspect it will be adopted by text editors, IDEs and possibly browser plug-ins as an easy way to test PHP code.

There’s no reason why you couldn’t use it on small internal server — and some people will try — but there are certainly more appropriate solutions. However, we could see a few interesting uses such as web application demonstrations which can run from a CD.

PHP 5.4 RC1 was released recently. I doubt you’ll need to wait long for the final version.

The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account