downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

Configurations INI> <Shell Interactif
[edit] Last updated: Fri, 24 May 2013

view this page in

Serveur web interne

Depuis PHP 5.4.0, le CLI SAPI fournit un serveur web interne.

Ce serveur web est prévu uniquement dans un but de développement, et ne doit pas être utilisé en production.

Les requêtes sont servies de façon séquentielle.

Les requêtes URI sont servies depuis le dossier de travail courant où PHP a été démarré, tant que l'option -t est utilisé pour spécifier explicitement un document racine. Si une requête URI ne spécifie pas un fichier, alors le fichier index.php ou le fichier index.html du dossier courant sera retourné. Si aucun de ces fichiers n'existe, alors un code réponse 404 sera retourné.

Si un fichier PHP est fourni dans la ligne de commande lorsque le serveur web est démarré, il sera traité comme un script "routeur". Le script sera exécuté au début de chaque requête HTTP. Si ce script retourne FALSE, alors la ressource demandée est retournée telle quelle. Sinon, la sortie du script est retournée au navigateur.

Les types MIME standards sont retournés pour les fichiers avec les extensions : .css, .gif, .htm, .html, .jpe, .jpeg, .jpg, .js, .png, .svg, et .txt. Les extensions .htm et .svg sont reconnues depuis PHP 5.4.4.

Exemple #1 Démarrage du serveur web

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

Le terminal affichera :

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

Après des requêtes URI sur http://localhost:8000/ et http://localhost:8000/myscript.html, le terminal affichera quelques choses comme :

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

Exemple #2 Démarrage avec un dossier racine spécifique

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

Le terminal affichera :

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

Exemple #3 Utilisation d'un script routeur

Dans cet exemple, le fait de demander des images les affichera, mais les requêtes pour les fichiers HTML afficheront "Bienvenue chez PHP !".

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/'$_SERVER["REQUEST_URI"])) {
    return 
false;    // retourne la requête telle quelle.
} else {
    echo 
"<p>Bienvenue chez PHP !</p>";
}
?>
$ php -S localhost:8000 router.php

Exemple #4 Vérification de l'utilisation CLI du serveur Web

Pour ré-utiliser un script router du framework lors du développement avec le CLI du serveur web et ensuite, continuez de l'utiliser avec un serveur web de production :

<?php
// router.php
if (php_sapi_name() == 'cli-server') {
    
/* Activation de la route statique et retourne FALSE */
}
/* on continue avec les opérations d'un index.php normal */
?>
$ php -S localhost:8000 router.php

Exemple #5 Gestion des types de fichiers non supportés

Si vous devez servir une ressource statique pour laquelle le type MIME n'est pas géré par le CLI du serveur web, utilisez ceci :

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

Exemple #6 Accès au CLI du serveur web depuis une machine distante

Vous pouvez rendre le serveur web accessible sur le port 8000 pour toutes les interfaces avec :

$ php -S 0.0.0.0:8000


Configurations INI> <Shell Interactif
[edit] Last updated: Fri, 24 May 2013
 
add a note add a note User Contributed Notes Serveur web interne - [6 notes]
up
1
zealotous at gmail dot com
10 months ago
There no problem to configure xdebug with php 5.4 built-in server.

If you debugging on local (dev) machine you need to :
1) add to php.ini:
zend_extention=/abosute/path/to/xdebug.dll
# USE ABSOLUTE PATH!!! relative path does not work.
#http://xdebug.org/docs/install
xdebug.remote_enable=1
2) run php from command line:
php.exe -S localhost:3000
3) check if xdebug loaded:
#index.php
<?php phpinfo(); ?>

4) configure NetBeans, Eclipse to work with localhost:3000

Notes: latest release of NetBeans 7.1,(7.2RC) (date july 2012)
seems to be unstable when working with build-in webserver and xdebug, but Eclipse PDT works fine.
up
0
Miguel Juan Semanino
11 months ago
Note: as of PHP 5.4.3 on Windows, $_ENV is an empty array for all incoming requests.
up
-1
matthewkastor at gmail dot com
8 months ago
The commandline webserver kept giving me 404's when I would request a directory. It would only automatically find index.php. Since I wanted links to subdirectories and index.html to be processed automatically, I made a router that does it. I left three handlers dangling out there to make it easy to process files, directories, or 404's. I was thinking this might be useful and that someone else might not like the way my auto index looks, so I tried to make this code easy to alter.

<?php
function atropa_router() {
    function
add_single_trailing_fslash($to) {
        if(!
$to) return '/';
        if(
substr($to, -1) !== '/') {
           
$to = $to . '/';
        }
        return
$to;
    }
   
    function
get_absolute_path_to_request() {
       
$p = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
        if(
is_null($p) ) {
           
$req = $_SERVER['DOCUMENT_ROOT'];
        } else {
           
$req = $_SERVER['DOCUMENT_ROOT'] . $p;
        }
        return
$req;
    }

    function
path_has_filename($req) {
       
$req = pathinfo($req, PATHINFO_BASENAME);
        if(
$req) {
            return
true;
        } else {
            return
false;
        }
    }

    function
web_index_exists($dir) {
        if(
is_file($dir . "/index.php") ) {
            return
true;
        } else {
            return
false;
        }
    }
   
    function
process_request() {
       
$req = get_absolute_path_to_request();

        if(
path_has_filename($req)) {
            if (
is_file($req)) {
                if(!
file_handler($req)) {
                    return
false; // serve the requested resource as-is.
               
}
            }
        }
        if(
is_dir($req)) {
            if (
web_index_exists($req)) {
                return
false;
            } elseif (
is_file($req . "/index.html")) {
               
$loc = add_single_trailing_fslash($_SERVER['REQUEST_URI']);
               
header('Location: ' . $loc . 'index.html');
                exit;
            } else {
               
directory_handler($req);
            }
        } else {
           
not_found_handler($req);
        }
    }

    if(
process_request() === false) {
        return
false;
    }
}
function
file_handler($req) {
    return
false;
}

function
directory_handler($req) {
   
$d = dir($req);
   
$p = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
   
$separator = '/';
   
$p = add_single_trailing_fslash($p);
    echo
'<!Doctype html><html><head><title>Directory</title></head><body>';
    echo
"Location: " . $d->path . '<br>';
    echo
'<table><tr><th>Name</th><th>Type</th></tr>';
    while (
false !== ($entry = $d->read())) {
        if(
$entry === '.') continue;
        if(
is_file($req . '/' . $entry)) {
           
$separator = '';
           
$type = 'File';
        } else {
           
$separator = '/';
           
$type = 'Directory';
        }
        echo
'<tr><td><a href="' . $p . $entry . $separator . '">' . $entry . '</a></td><td>' . $type . '</td></tr>';
    }
   
$d->close();
    echo
'</table></body></html>';
}

function
not_found_handler($req) {
   
header('HTTP/1.1 404 Not Found');
    echo
'<!Doctype html><html><head><title>404</title></head><body><p>Requested resource could not be found</p></body></html>';
}
return
atropa_router();
?>
up
-1
Stefano F. Rausch
1 year ago
To develop / deploy websites in 3 stages, i.e. ( 1 ) locally, ( 2 ) with an access controlled dedicated beta / test website in the www and ( 3 ) the production site, you can have ( 1 ) & ( 2 ) using the same domain name - port free - as follows:

- look up the IP address of the beta.web.site

and edit the hosts file to reflect:

- <IP> beta.web.site
- 127.0.0.1 beta.web.site

Start the built-in web server to work locally with:

- sudo php -S beta.web.site:80

and just hit http://beta.web.site as usual. Switching back and forth between ( 1 ) and ( 2 ) is as easy as telling the php engine not to fake a server any more :) Nice!

Happy PHP'ing.
up
-2
matthewkastor at gmail dot com
8 months ago
Updated Autoindex router for PHP built in server

<?php
/**
 * Rev. 2 Autoindex Router for PHP built in webserver
 * Fixes error where given http://localhost/? and localhost
 * only contains index.html, the router redirects endlessly.
 */
function atropa_router() {
    function
add_single_trailing_fslash($to) {
        if(!
$to) return '/';
        if(
substr($to, -1) !== '/') {
           
$to = $to . '/';
        }
        return
$to;
    }
   
    function
get_request_uri_path() {
       
$p = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
        if(
is_null($p) ) {
           
$req = '/';
        } else {
           
$req = $p;
        }
        return
$req;
    }
   
    function
get_absolute_path_to_request() {
        return
$_SERVER['DOCUMENT_ROOT'] . get_request_uri_path();
    }

    function
path_has_filename($req) {
       
$req = pathinfo($req, PATHINFO_BASENAME);
        if(
$req) {
            return
true;
        } else {
            return
false;
        }
    }

    function
web_index_exists($dir) {
        if(
is_file($dir . "index.php") ) {
            return
true;
        } else {
            return
false;
        }
    }
   
    function
process_request() {
       
$req = get_absolute_path_to_request();

        if(
path_has_filename($req)) {
            if (
is_file($req)) {
                if(!
file_handler($req)) {
                    return
false; // serve the requested resource as-is.
               
}
            }
        }
        if(
is_dir($req)) {
           
$req = add_single_trailing_fslash($req);
            if (
web_index_exists($req)) {
                return
false;
            } elseif (
is_file($req . "index.html")) {
               
$loc = get_request_uri_path();
               
$loc = add_single_trailing_fslash($loc);
               
header('Location: ' . $loc . 'index.html');
                exit;
            } else {
               
directory_handler($req);
            }
        } else {
           
not_found_handler($req);
        }
    }

    if(
process_request() === false) {
        return
false;
    }
}

function
file_handler($req) {
    return
false;
}

function
directory_handler($req) {
   
$d = dir($req);
   
$p = get_request_uri_path();
   
$p = add_single_trailing_fslash($p);
    echo
'<!Doctype html><html><head><title>Directory</title></head><body>';
    echo
"Location:  $d->path <br>";
    echo
'<table><tr><th>Name</th><th>Type</th></tr>';
    while (
false !== ($entry = $d->read())) {
        if(
$entry === '.') continue;
       
$href = $p . $entry;
        if(
is_file($req . $entry)) {
           
$type = 'File';
        } else {
           
$href = add_single_trailing_fslash($href);
           
$type = 'Directory';
        }
        echo
"<tr><td><a href='$href'>$entry</a></td><td>$type</td></tr>";
    }
   
$d->close();
    echo
'</table></body></html>';
}

function
not_found_handler($req) {
   
header('HTTP/1.1 404 Not Found');
    echo
'<!Doctype html><html><head><title>404</title></head><body><p>Requested resource could not be found</p></body></html>';
}

return
atropa_router();
?>
up
-1
dstrout at dstrout dot net
1 month ago
Just gave it a try, and it is IPv6 compatible, if anyone was wondering.

 
show source | credits | sitemap | contact | advertising | mirror sites