php[tek] 2018 : Call for Speakers

Web server interno


Questo server web è stato sviluppato per aiutare lo sviluppo di applicazioni. Può anche essere utile per scopo di test o per dimostrazioni applicative che sono eseguite in ambienti controllati. Non è destinato ad essere un web server con tutte le funzionalità. Non dovrebbe essere usato su una rete pubblica.

A partire da PHP 5.4.0, la CLI SAPI fornisce un web server interno.

Le applicazioni PHP andranno in stallo se una richiesta è bloccata.

Le richieste URI sono eseguite dalla cartella di lavoro corrente, in cui PHP è stato eseguito, a meno che non sia stata usata l'opzione -t per specificare una radice dei documenti. Se una richiesta URI non specifica un file, allora viene restituito o index.php o index.html nella directory data. Se i file non esistono, allora una risposta con codice 404 viene restituita.

Se un file PHP viene specificato sulla linea di comando quando viene attivato il web server, viene trattato come script "router" per il web server. Lo script è eseguito all'inizio di ogni richiesta HTTP. Se restituisce FALSE, la risorsa richiesta viene ritornata così com'è. altrimenti viene restituito al browser il risultato dello script.

I tipi MIME standard vengono restituiti per i file con le estensioni: 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, e .zip.

Changelog: Tipi MIME Supportati (estensioni dei file)
Versione Descrizione
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 Avvio del web server

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

Il terminale mostrerà:

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

Dopo le richiste URI per http://localhost:8000/ e http://localhost:8000/myscript.html il terminale mostrerà qualcosa di simile a:

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 Esecuzione con una cartella di radice dei documenti specifica

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

Il terminale mostrerà:

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 Uso di uno script router

In questo esempio, le richieste per delle immagini le mostreranno, ma richieste per file HTML mostreranno "Welcome to PHP":

// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/'$_SERVER["REQUEST_URI"])) {
false;    // serve la risorsa richiesta così com'è.
} else { 
"<p>Welcome to PHP</p>";
$ php -S localhost:8000 router.php

Example #4 Controllo dell'Uso del Server Web CLI

Per riutilizzare uno script del router del framework durante lo sviluppo con il web server CLI e successivamente anche con un server web di produzione:

// router.php
if (php_sapi_name() == 'cli-server') {
/* route static assets and return false */
/* prosegue con le normali operazioni di index.php */
$ php -S localhost:8000 router.php

Example #5 Gestione Tipi File Non Supportati

Se si ha bisogno di restituire una risorsa statica il cui tipo MIME non viene gestito dal web server CLI, utilizzare:

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

Example #6 Accedere Al Web Server CLI Da Macchine Remote

È possibile rendere accessibile il web server sulla porta 8000 per qualsiasi interfaccia con:

$ php -S
add a note add a note

User Contributed Notes 16 notes

jonathan at reinink dot ca
3 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()).
oan at vizrt dot com
10 months ago
I painfully experienced behaviour that I can't seem to find documented here so I wanted to save everyone from repeating my mistake by giving the following heads up:

When starting php -S on a mac (in my case macOS Sierra) to host a local server, I had trouble with connecting from legacy Java.

As it turned out, if you started the php server with
"php -S localhost:80"
the server will be started with ipv6 support only!

To access it via ipv4, you need to change the start up command like so:
"php -S"
which starts server in ipv4 mode only.
Mark Simon
1 year ago
It’s not mentioned directly, and may not be obvious, but you can also use this to create a virtual host. This, of course, requires the help of your hosts file.

Here are the steps:

1    /etc/hosts

2    cd [root folder]
    php -S

3    Browser:

Combined with a simple SQLite database, you have a very handy testing environment.
matthes at leuffen dot de
1 year ago
To output debugging information on the command line you can write output to php://stdout:


file_put_contents("php://stdout", "\nRequested: $path");
"<p>Hello World</p>";
Ivan Ferrer
4 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.
tamas at bartatamas dot hu
3 years 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'].

dwingardjr at gmail dot com
3 months ago
Just a note to people who also use windows 8.1, or anyone who has had this problem when running the using the PHP server CLI.

`PHP -S localhost:8000 -t /public` <-- Not going to work.

`PHP -S localhost:8000 -t public` <-- Works!

And there is something else up in the notes saying something about you can't serve a project folder and a router file. Well, actually you can! At least for me.

`PHP -S localhost:8000 router.php -t public` <-- Perhaps someone tries this and it doesn't work.

`PHP -S localhost:8000 -t public router.php` <-- Works!
gyunaev at gmail dot com
4 months ago
You can also print messages to the server's STDOUT via error_log().

Also the documentation doesn't make it clear that when you use router script if a PHP file is requested and you return false, the PHP file will be served (i.e. you do not need to load and eval it manually).
eyecatchup at gmail dot com
5 months ago
Note: The built-in web server has a file size limit. For files larger than 5 GB, it will always serve a "File not found" error page.
simonbengt at gmail dot com
2 years 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.
ohcc at 163 dot com
11 months ago
$_SERVER['SERVER_ADDR'] is not defined when using php as the built-in commandline web server, so you can not use $_SERVER['SERVER_ADDR'] to detect the Server's IP address.

P.S.: This is tested on Windows with PHP 7.1 on 2016-12-22.

Below is the printed $_SERVER variable.

    [DOCUMENT_ROOT] => E:\Programs\PHPServer\www\srv
    [REMOTE_ADDR] =>
    [REMOTE_PORT] => 10865
    [SERVER_SOFTWARE] => PHP 7.1.0 Development Server
    [SERVER_NAME] =>
    [SERVER_PORT] => 8080
    [REQUEST_URI] => /
    [SCRIPT_NAME] => /index.php
    [SCRIPT_FILENAME] => E:\Programs\PHPServer\www\srv\index.php
    [PHP_SELF] => /index.php
    [HTTP_HOST] =>
    [HTTP_CONNECTION] => keep-alive
    [HTTP_CACHE_CONTROL] => max-age=0
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    [HTTP_DNT] => 1
    [HTTP_ACCEPT_ENCODING] => gzip, deflate, sdch
    [HTTP_ACCEPT_LANGUAGE] => zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
    [HTTP_COOKIE] => qbbs_2132_saltkey=fZ7509n5; qbbs_2132_lastvisit=1482156014; Hm_lvt_f812a4362ef73c80c4d13485d1ab3a49=1482159614; _ga=GA1.2.1594404236.1482159615; su=727vL6EEPLqjcyfJcad-za9eVYOh1i7e; Hm_lvt_6a65b0f2004e441e86ecea9c3562d997=1482232509,1482241896,1482242293,1482296586
    [REQUEST_TIME_FLOAT] => 1482390410.65625
    [REQUEST_TIME] => 1482390410
php dot chaska at xoxy dot net
2 years 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/
leandro at leandroleite dot info
1 year ago
when I need to up a server for develop with rewrite, I use it:

// php -S -file webServer.php

// webServer.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]]}");
ohcc at 163 dot com
1 year ago
Do NOT use the -t option if you want to use a router script, you can change current working directory to the web document root before launching the php built-in web server.

[works fine]

cd /d C:\Web\Server
php -S router.php -n -d expose_php=0 -d display_errors=0 -d extension_dir="ext"

[always gets a 500 error]

php -S router.php -t C:\Web\Server -n -d expose_php=0 -d display_errors=0 -d extension_dir="ext"
1 year 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"
arsensafarian1984 at gmail dot com
1 month ago
submit_btn.addEventListener(MouseEvent.CLICK, sendMessage);
function sendMessage(e:MouseEvent):void{
var my_vars:URLVariables = new URLVariables();
my_vars.senderName = name_txt.text;
my_vars.senderEmail = email_txt.text;
my_vars.senderMsg = message_txt.text;

var my_url:URLRequest = new URLRequest("mail.php");
my_url.method = URLRequestMethod.POST; = my_vars;

var my_loader:URLLoader = new URLLoader();
my_loader.dataFormat = URLLoaderDataFormat.VARIABLES;

name_txt.text = "";
email_txt.text = "";
message_txt.text = "Message Sent";

To Top