PHP 7.1.0 Alpha 2 Released

Built-in web server

Warning

This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

The web server runs a only one single-threaded process, so PHP applications will stall if a request is blocked.

URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root. If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, the lookup for index.php and index.html will be continued in the parent directory and so on until one is found or the document root has been reached. If an index.php or index.html is found, it is returned and $_SERVER['PATH_INFO'] is set to the trailing part of the URI. Otherwise a 404 response code is returned.

If a PHP file is given on the command line when the web server is started it is treated as a "router" script. The script is run at the start of each HTTP request. If this script returns FALSE, then the requested resource is returned as-is. Otherwise the script's output is returned to the browser.

Standard MIME types are returned for files with extensions: .3gp, .apk, .avi, .bmp, .css, .csv, .doc, .docx, .flac, .gif, .gz, .gzip, .htm, .html, .ics, .jpe, .jpeg, .jpg, .js, .kml, .kmz, .m4a, .mov, .mp3, .mp4, .mpeg, .mpg, .odp, .ods, .odt, .oga, .ogg, .ogv, .pdf, .pdf, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx, .xml, .xsl, .xsd, and .zip.

Changelog: Supported MIME Types (file extensions)
Version Description
5.5.12 .xml, .xsl, and .xsd
5.5.7 .3gp, .apk, .avi, .bmp, .csv, .doc, .docx, .flac, .gz, .gzip, .ics, .kml, .kmz, .m4a, .mp3, .mp4, .mpg, .mpeg, .mov, .odp, .ods, .odt, .oga, .pdf, .pptx, .pps, .qt, .swf, .tar, .text, .tif, .wav, .wmv, .xls, .xlsx, and .zip
5.5.5 .pdf
5.4.11 .ogg, .ogv, and .webm
5.4.4 .htm and .svg

Example #1 Starting the web server

$ cd ~/public_html
$ php -S localhost:8000

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit

After URI requests for http://localhost:8000/ and http://localhost:8000/myscript.html the terminal will show something similar to:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read
[Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read
[Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read
[Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read
[Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request read

Example #2 Starting with a specific document root directory

$ cd ~/public_html
$ php -S localhost:8000 -t foo/

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011
Listening on localhost:8000
Document root is /home/me/public_html/foo
Press Ctrl-C to quit

Example #3 Using a Router Script

In this example, requests for images will display them, but requests for HTML files will display "Welcome to 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>";
}
?>
$ php -S localhost:8000 router.php

Example #4 Checking for CLI Web Server Use

To reuse a framework router script during development with the CLI web server and later also with a production web server:

<?php
// router.php
if (php_sapi_name() == 'cli-server') {
    
/* route static assets and return false */
}
/* go on with normal index.php operations */
?>
$ php -S localhost:8000 router.php

Example #5 Handling Unsupported File Types

If you need to serve a static resource whose MIME type is not handled by the CLI web server, use:

<?php
// router.php
$path pathinfo($_SERVER["SCRIPT_FILENAME"]);
if (
$path["extension"] == "el") {
    
header("Content-Type: text/x-script.elisp");
    
readfile($_SERVER["SCRIPT_FILENAME"]);
}
else {
    return 
FALSE;
}
?>
$ php -S localhost:8000 router.php

Example #6 Accessing the CLI Web Server From Remote Machines

You can make the web server accessible on port 8000 to any interface with:

$ php -S 0.0.0.0:8000
add a note add a note

User Contributed Notes 11 notes

up
47
jonathan at reinink dot ca
2 years ago
In order to set project specific configuration options, simply add a php.ini file to your project, and then run the built-in server with this flag:

php -S localhost:8000 -c php.ini

This is especially helpful for settings that cannot be set at runtime (ini_set()).
up
24
Ivan Ferrer
2 years ago
On Windows you may find useful to have a phpserver.bat file in shell:sendto with the folowing:
explorer http://localhost:8888
rem check if arg is file or dir
if exist "%~1\" (
  php -S localhost:8888 -t "%~1"
) else (
  php -S localhost:8888 -t "%~dp1"
)

then for fast web testing you only have to SendTo a file or folder to this bat and it will open your explorer and run the server.
up
7
php dot chaska at xoxy dot net
10 months ago
Note that to listen on a naked IPv6 address, you have to strangely enclose the address in so-called square brackets.  Example:

$ php -S [9990:116:a001:1900::1001]:8080 -t web/
up
7
tamas at bartatamas dot hu
1 year ago
If your URI contains a dot, you'll lose the $_SERVER['PATH_INFO'] variable, when using the built-in webserver.
I wanted to write an API, and use .json ending in the URI-s, but then the framework's routing mechanism broke, and it took a lot of time to discover that the reason behind it was its router relying on $_SERVER['PATH_INFO'].

References:
https://bugs.php.net/bug.php?id=61286
up
9
dstrout at dstrout dot net
3 years ago
Just gave it a try, and it is IPv6 compatible, if anyone was wondering.
up
2
simonbengt at gmail dot com
1 year ago
My routing file looks like this:

if (file_exists($_SERVER["DOCUMENT_ROOT"] . $_SERVER["REQUEST_URI"])) {
    return false;
} else {
    require "index.php";
}

The reason is to support all static files.
up
1
synnus at gmail dot com
1 month ago
<?php

   
/*
     *  Web serv mod v2 with  ./WWW/
     *
     */

$request_uri = '.'.urldecode($_SERVER['REQUEST_URI']);
//var_dump($request_uri);
if($request_uri == './' ) { $request_uri = './www'; }

if(
is_dir($request_uri) ){

   
// server use the relative directory
   
$dirname = preg_replace('/\/{2}/', '/', $request_uri.'/');

   
// browser use the absolute path_name which bases on the server root directory
   
$browser_path = preg_replace('/^\./', '', $dirname);
   
   
$ex = explode('/',$browser_path);
   
   
$g = '../';
    foreach(
$ex as $k => $l) {
        echo
'<a href="../' . $g. '">' . str_ireplace('//' , '/' ,($l == ''  ?   '' $g . '/'  )) . '</a>';
       
$g = $l ;
    }
    echo
'<br />', PHP_EOL;
   
   
$files_arr = '';
   
$d = dir($dirname);
   
//echo $d->path , '<br />', PHP_EOL;

   
while (false !== ($entry = $d->read())) {
       if(
$entry != '.') {
           if(
is_dir($d->path . $entry) ){
               
$files_arr .= '<a href="' . $browser_path . $entry . '"> <img src="http://127.0.0.1:8000/res/folder.png" /> ' . $entry . '</a><br />' . PHP_EOL;
           }
           else {
              
$files_arr .= '<a href="' . $browser_path . $entry . '"> <img src="http://127.0.0.1:8000/res/file.png" /> ' . $entry . '</a><br />' . PHP_EOL;
           }
       }
    }
   
$d->close();

   

   echo
'<!DOCTYPE HTML>
            <html>
                <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
                </head>
                <body>
                    '
, $files_arr,'
                </body>
            </html>'
;
}else{
   
   
//$exp_url = explode('/',$request_uri);
   
   
   
@header('Content-Type: ' . @mime_content_type($request_uri));
   
//echo file_get_contents('www/' . $request_uri);
   
   
$handle = @fopen($request_uri, "rb");
    if (
FALSE === $handle) {
        exit(
"Echec lors de l'ouverture du flux vers l'URL");
    }

    while (!
feof($handle)) {
        echo
fread($handle, 8192);
    }
   
   
fclose($handle);

}

?>
up
0
gabe at fijiwebdesign dot com
1 month ago
Here's a router.php that will show directory listings and allow traversal of the directories as well as load index.html and index.php from the directory if they exist.

<?php

// router for php built in server to show directory listings.
// php -S localhost:8001 router.php

$path = $_SERVER['DOCUMENT_ROOT'] . $_SERVER["REQUEST_URI"];
$uri = $_SERVER["REQUEST_URI"];

// let server handle files or 404s
if (!file_exists($path) || is_file($path))  {
    return
false;
}

// append / to directories
if (is_dir($path) && $uri[strlen($uri) -1] != '/') {
   
header('Location: ' . $uri . '/');
}

// send index.html and index.php
$indexes = ['index.php', 'index.html'];
foreach(
$indexes as $index) {
   
$file = $path . '/' . $index;
    if (
is_file($file)) {
        return require(
$file);
    }
}

// show directory list
echo "<h2>Index of " . $uri . "</h2>";
$g = array_map(function($path) {
    if (
is_dir($path)) {
       
$path .= '/';
    }
    return
str_replace('//', '/', $path);
},
glob($path . '/*'));

usort($g, function($a,$b) {
    if(
is_dir($a) == is_dir($b))
        return
strnatcasecmp($a,$b);
    else
        return
is_dir($a) ? -1 : 1;
});

echo
implode("<br>", array_map(function($a) {
   
$url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $a);
    return
'<a href="' . $url . '">' . substr($url, 1) . '</a>';
},
$g));

?>
up
0
@salmanapk
2 months ago
I improved Ivan Ferrer's phpserver.bat to open the Send To'd files in the browser directly:-

rem check if arg is file or dir
if exist "%~1\" (
  explorer http://localhost:8888
  php -S localhost:8888 -t "%~1"
) else (
  explorer http://localhost:8888/%~nx1
  php -S localhost:8888 -t "%~dp1"
)
up
0
yuanoook at gmail dot com
2 months ago
This is my local php server

<?php
$request_uri
= '.'.urldecode($_SERVER['REQUEST_URI']);
if(
is_dir($request_uri) ){

   
// server use the relative directory
   
$dirname = preg_replace('/\/{2}/', '/', $request_uri.'/');

   
$files_arr = array_filter(scandir($dirname), function($file_name){
        return
false == (bool)preg_match('/^\.+/', $file_name);
    });

   
// browser use the absolute path_name which bases on the server root directory
   
$browser_path = preg_replace('/^\./', '', $dirname);

   
printf('<!DOCTYPE HTML>
            <html>
                <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
                </head>
                <body>
                    %s
                </body>
            </html>'
,
           
implode(
               
preg_replace('/^(.*)$/', '<a href="'.$browser_path.'${1}">${1}</a>', $files_arr),
               
'<br/>'
           
)
        );
}else{
   
header('Content-Type: '.mime_content_type($request_uri));
    echo
file_get_contents($request_uri);
}
up
-1
leandro at leandroleite dot info
4 months ago
when I need to up a server for develop with rewrite, I use it:

// php -S 0.0.0.0:8080 -file webServer.php

// webServer.php
<?php
if (preg_match('/\.css|\.js|\.jpg|\.png|\.map$/', $_SERVER['REQUEST_URI'], $match)) {
   
$mimeTypes = [
       
'.css' => 'text/css',
       
'.js'  => 'application/javascript',
       
'.jpg' => 'image/jpg',
       
'.png' => 'image/png',
       
'.map' => 'application/json'
   
];
   
$path = __DIR__ . $_SERVER['REQUEST_URI'];
    if (
is_file($path)) {
       
header("Content-Type: {$mimeTypes[$match[0]]}");
        require
$path;
        exit;
    }
}
require_once
__DIR__.'/../app/bootstrap.php';
To Top