Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Using PHP's Built-In Server: A Quick Guide to `php -S`

1 min read .
Using PHP's Built-In Server: A Quick Guide to `php -S`

When developing PHP applications, especially small projects or prototypes, configuring a full web server such as Apache or Nginx can be unnecessary. PHP includes a lightweight development server that starts with a single command: php -S.

It is convenient for local development and quick testing, but it is not designed for production traffic.

What Is php -S?

php -S starts PHP’s built-in development web server. It can serve PHP scripts and static files without a separate web-server configuration.

Start the Built-In Server

Navigate to your PHP project’s document root and run:

php -S localhost:8000

The application is then available at http://localhost:8000.

Serve a Specific Directory

By default, the current directory is used as the document root. To choose another directory, use -t:

php -S localhost:8000 -t /path/to/your/directory

Use a Custom Router Script

The built-in server can also run a router script, which is useful for front-controller applications and custom routing during development.

Create router.php:

<?php
if (php_sapi_name() === 'cli-server') {
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    if (file_exists(__DIR__ . $path)) {
        return false; // Serve existing files directly
    }
}

// Custom routing logic
require __DIR__ . '/index.php';

Start the server with that router:

php -S localhost:8000 router.php

Existing files are served directly, while other requests are passed to index.php.

Why Use It?

  • Simple: no separate Apache or Nginx configuration is required.
  • Portable: available anywhere the PHP CLI is installed.
  • Fast to start: useful for examples, prototypes, and local tests.
  • Developer-friendly: PHP errors appear directly in the development workflow.

Limitations

  • Development only: PHP’s documentation explicitly positions this server for development and testing rather than public production use.
  • Limited server features: it does not behave like Apache or Nginx and does not process .htaccess rules.
  • Concurrency characteristics vary by platform and PHP version: do not design production capacity around the built-in server.

Conclusion

php -S is a practical way to run a PHP project locally with almost no setup. Use it for development, experiments, tutorials, and quick testing, then deploy production applications behind a production-grade web server or application runtime appropriate to your environment.

Related Posts

chevron-up