How To Use PHP Built-in Web Server

In php on 2~4 minutes Post a comment

PHP has its own built-in web server starting from PHP 5.4 and we can use it to quickly run PHP scripts and applications. Let’s see how can we use it for local development and testing purposes. In the end, we explain how to run PHP built-in web server using Docker even if you do not have PHP installed on your PC.

Start PHP Built-in Web Server For Current Directory

Run the following command to start the PHP built-in web server with the address and port. Normally, address can be 127.0.0.1, localhost or 0.0.0.0. Port can be any unused port in the valid range (1~65535).

php -S 127.0.0.1:8000

Start PHP Built-in Web Server For A Document Root

We can use the -t option to specify a different directory as the document root (docroot). In this case, it is the public directory.

php -S 127.0.0.1:8080 -t public

Start PHP Built-in Web Server With A Router File

Usually, when we request a file from a web server, first it tries to find the directory or file specified in the request. However, sometimes we need to override this behaviour by pushing every single request to a specific file which ultimately decides the destination resource to be served.

php -S 127.0.0.1:8080 router.php

Altogether, we can mention the document root and the router file like below.

php -S 127.0.0.1:8080 -t public router.php

Start PHP Built-in Web Server With Docker

For those who do not have PHP installed on their PCs can use Docker to start a PHP built-in web server like the below.

We are using the following options.

  • --rm to remove the container once it is exited.
  • -u $(id -u):$(id -g) to run all scripts as the current user.
  • -v $(pwd):/app to mount the current directory into the /app directory in the container.
  • -p 8080:80 to expose and publish port 80 in the container to port 8080 in the host.
  • --name php to name the container.
  • php:8.1.5-cli-alpine3.15 is the Docker image we are using. Visit Docker Hub to use a different version. Change both document root -t /app and mounting directory /app if you need.
docker run --rm \
    -u $(id -u):$(id -g) \
    -v $(pwd):/app \
    -p 8080:80 \
    --name php \
    php:8.1.5-cli-alpine3.15 php -S 0.0.0.0:80 -t /app

PHP built-in web server is recommended for local development and testing purposes only. Never use it for production environments. Visit https://www.php.net/manual/en/features.commandline.webserver.php to learn more about the PHP built-in web server.

Share:
You May Also Like: