How to Use PHP's Built-in Web Server

Advertisement

Advertisement

PHP has a built in web server that was introduced in version 5.4.0. It is not suited for production but is great for easy development or quick testing. Here are a few ways to use it.

Serve Current Directory

To serve your current working directory locally, use

php -S localhost:8000

To bind to all interfaces, allowing remote computers to connect, use 0.0.0.0 instead.

php -S 0.0.0.0:8000

Serving a Specific Directory

Use the -t option to specify a target directory to serve.

php -S localhost:8000 -t foo/

Serve a Specific File

php -S localhost:8000 router.php

Determine Source of Request

It may be useful to know if the request is coming through the web server or if the script is being run directly.

if (php_sapi_name() == 'cli-server') {
    // Request did come through built-in web server
}

Advertisement

Advertisement