Servidor web interno

Advertencia

Este servidor web está destinado a ayudar en el desarrollo de aplicaciones. También puede ser útil para pruebas y para demostraciones de aplicaciones que se ejecutan en entornos controlados. Sin embargo, no está diseñado para ser un servidor web completo. Por lo tanto, no debe utilizarse en una red pública.

El CLI SAPI proporciona un servidor web interno.

El servidor web se ejecuta en un solo proceso single-threaded, las aplicaciones PHP se retrasarán/suspenderán si una solicitud está bloqueada.

Las solicitudes URI se sirven desde el directorio de trabajo actual donde se inició PHP, a menos que se utilice la opción -t para especificar explícitamente un documento raíz. Si una solicitud URI no especifica un archivo, entonces el archivo index.php o el archivo index.html del directorio actual será devuelto. Si ninguno de estos archivos existe, la búsqueda de un archivo index.php e index.html continuará en el directorio padre y así sucesivamente hasta que se encuentre uno de estos archivos o se alcance el directorio raíz. Si se encuentra un archivo index.php o index.html, se devolverá y $_SERVER['PATH_INFO'] se establecerá como la última parte de la URI. De lo contrario, se devolverá un código de respuesta 404.

Si se proporciona un archivo PHP en la línea de comandos cuando se inicia el servidor web, se tratará como un script "ruteador". El script se ejecutará al inicio de cada solicitud HTTP. Si este script devuelve false, entonces el recurso solicitado se devolverá tal cual. De lo contrario, la salida del script se devolverá al navegador.

Los tipos MIME estándar se devuelven para archivos con las extensiones: .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, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx, .xml, .xsl, .xsd, .zip .

A partir de PHP 7.4.0, el servidor web integrado puede configurarse para bifurcar varios trabajadores para probar código que requiere múltiples solicitudes concurrentes al servidor web integrado. Establezca la variable de entorno PHP_CLI_SERVER_WORKERS en el número de trabajadores deseados antes de iniciar el servidor.

Nota: Esta funcionalidad no está soportada en Windows.

Advertencia

Esta funcionalidad experimental no está destinada a ser utilizada en producción. En general, el Servidor Web integrado no está destinado a ser utilizado en producción.

Ejemplo #1 Inicio del servidor web

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

El terminal mostrará:

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

Después de las solicitudes URI a http://localhost:8000/ y http://localhost:8000/myscript.html, el terminal mostrará algo como:

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

Tenga en cuenta que antes de PHP 7.4.0, los recursos estáticos en enlace simbólico no son accesibles en Windows, a menos que el script ruteador lo maneje.

Ejemplo #2 Inicio con un directorio raíz específico

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

El terminal mostrará:

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

Ejemplo #3 Uso de un script ruteador

En este ejemplo, solicitar imágenes las mostrará, pero las solicitudes de archivos HTML mostrarán "¡Bienvenido a PHP!".

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return
false; // devuelve la solicitud tal cual.
} else {
echo
"<p>¡Bienvenido a PHP!</p>";
}
?>
$ php -S localhost:8000 router.php

Ejemplo #4 Verificación de la utilización de CLI del servidor web

Para reutilizar un script ruteador del marco durante el desarrollo con el CLI del servidor web y luego continuar utilizándolo con un servidor web de producción:

<?php
// router.php
if (php_sapi_name() == 'cli-server') {
/* Activar la ruta estática y devolver FALSE */
}
/* continuar con las operaciones de un index.php normal */
?>
$ php -S localhost:8000 router.php

Ejemplo #5 Manejo de tipos de archivos no soportados

Si necesita servir un recurso estático para el cual el tipo MIME no es manejado por el CLI del servidor web, use esto:

<?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

Ejemplo #6 Acceso al CLI del servidor web desde una máquina remota

Puede hacer que el servidor web sea accesible en el puerto 8000 para todas las interfaces con:

$ php -S 0.0.0.0:8000
Advertencia

El servidor web integrado no debe utilizarse en una red pública.

add a note

User Contributed Notes 8 notes

up
129
jonathan at reinink dot ca
12 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
81
Mark Simon
9 years 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
    127.0.0.1    www.example.com

2    cd [root folder]
    php -S www.example.com:8000

3    Browser:
    http://www.example.com:8000/index.php

Combined with a simple SQLite database, you have a very handy testing environment.
up
55
oan at vizrt dot com
9 years 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 127.0.0.1:80"
which starts server in ipv4 mode only.
up
33
tamas at bartatamas dot hu
11 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'].

References:
https://bugs.php.net/bug.php?id=61286
up
27
matthes at leuffen dot de
9 years ago
To output debugging information on the command line you can write output to php://stdout:

<?php
$path = $_SERVER["SCRIPT_FILENAME"];

file_put_contents("php://stdout", "\nRequested: $path");
echo "<p>Hello World</p>";
?>
up
30
Ivan Ferrer
12 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
14
deep at deepshah dot me
5 years ago
Listen on all addresses of IPv4:
php -S 0.0.0.0:80

Listen on all addresses of IPv6:
php -S [::0]:80
up
0
sony at sony-ak dot com
6 years ago
To send environment variable as long as with PHP built-in web server, type like this.

~$ MYENV=dev php -d variables_order=EGPCS -S 0.0.0.0:8000

On PHP script we can check with this code.

<?php
  echo getenv('MYENV'); // print dev
To Top