PHP server on local machine?

PHP 5.4 and later have a built-in web server these days.

You simply run the command from the terminal:

cd path/to/your/app
php -S 127.0.0.1:8000

Then in your browser go to http://127.0.0.1:8000 and boom, your system should be up and running. (There must be an index.php or index.html file for this to work.)

You could also add a simple Router

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
} else { 
    require_once('resolver.php');
}
?>

And then run the command

php -S 127.0.0.1:8000 router.php

References:

  • https://www.php.net/manual/en/features.commandline.webserver.php
  • https://www.php.net/manual/en/features.commandline.options.php

Install and run XAMPP: http://www.apachefriends.org/en/xampp.html


This is a simple, sure fire way to run your php server locally:

php -S 0.0.0.0:<PORT_NUMBER>

Where PORT_NUMBER is an integer from 1024 to 49151

Example: php -S 0.0.0.0:8000

Notes:

  1. If you use localhost rather than 0.0.0.0 you may hit a connection refused error.

  2. If want to make the web server accessible to any interface, use 0.0.0.0.

  3. If a URI request does not specify a file, then either index.php or index.html in the given directory are returned.

Given the following file (router.php)

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
} else { 
    echo "<p>Welcome to PHP</p>";
}
?>

Run this ...

php -S 0.0.0.0:8000 router.php

... and navigate in your browser to http://localhost:8000/ and the following will be displayed:

Welcome to PHP

Reference:

Built-in web server

Tags:

Php

Local

Server