Using PHP’s Built-in Web Server

If you want to check out how some PHP code you’re writing behaves with real requests from a web browser, a quick way to dive in is to use the PHP engine’s built-in web server.

Run php with a -S argument that provides a hostname and port number, and you’ve got a running web server providing access to the files in whatever directory you ran php in. For example, to run the web server on port 8000 of your local machine, run php -S localhost:8000. With that server running, visiting http://localhost:8000/ pizza.php causes the web server to execute the code in pizza.php and send the results back to your web browser.

If the web server is not finding files that you think it should, check what directory you were in when you ran the php -S command. By default, the PHP web server serves up files in the directory that you ran php -S in (and below). To provide an alternate document root directory, add a -t argument. For example, php -S local host:8000 -t /home/mario/web serves up the files under /home/mario/web at http:// localhost:8000.

The PHP web server doesn’t do anything fancy to map URLs to files. It just looks for a filename under its base directory as specified in the URL. If you leave a filename out of the URL, it looks for index.php and index.html before returning a “file not found” error.

The built-in web server only handles one request at a time. It is best for testing func­tionality and experiments on a development machine. It’s much easier to get up and running than a big Apache or nginx installation that you’d need to configure, but it also is not as full-featured. When it’s time to deploy your code to a production envi­ronment, use a web server that can handle the scale and security requirements of gen­eral usage.

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

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