CLI SAPI 提供了一個內(nèi)置的Web服務(wù)器。
這個內(nèi)置的Web服務(wù)器主要用于本地開發(fā)使用,不可用于線上產(chǎn)品環(huán)境。
URI請求會被發(fā)送到PHP所在的的工作目錄(Working Directory)進行處理,除非你使用了-t參數(shù)來自定義不同的目錄。
如果請求未指定執(zhí)行哪個PHP文件,則默認執(zhí)行目錄內(nèi)的index.php 或者 index.html。如果這兩個文件都不存在,服務(wù)器會返回404錯誤。
當(dāng)你在命令行啟動這個Web Server時,如果指定了一個PHP文件,則這個文件會作為一個“路由”腳本,意味著每次請求都會先執(zhí)行這個腳本。如果這個腳本返回 false
,那么直接返回請求的文件(例如請求靜態(tài)文件不作任何處理)。否則會把輸出返回到瀏覽器。
示例 #1 啟動Web服務(wù)器
$ cd ~/public_html $ php -S localhost:8000
終端窗口會顯示:
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
接著訪問http://localhost:8000/和http://localhost:8000/myscript.html,窗口會顯示:
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
示例 #2 啟動時指定根目錄
$ cd ~/public_html $ php -S localhost:8000 -t foo/
終端窗口顯示:
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
示例 #3 使用路由(Router)腳本
請求圖片直接顯示圖片,請求HTML則顯示“Welcome to PHP”
<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"]))
return false; // 直接返回請求的文件
else {
echo "<p>Welcome to PHP</p>";
}
?>
$ php -S localhost:8000 router.php
執(zhí)行之后終端顯示:
PHP 5.4.0 Development Server started at Thu Jul 21 10:53:19 2011 Listening on localhost:8000 Document root is /home/me/public_html Press Ctrl-C to quit. [Thu Jul 21 10:53:45 2011] ::1:55801 GET /mylogo.jpg - Request read [Thu Jul 21 10:53:52 2011] ::1:55803 GET /abc.html - Request read [Thu Jul 21 10:53:52 2011] ::1:55804 GET /favicon.ico - Request read
示例 #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
示例 #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
示例 #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
The built-in Web Server should not be used on a public network.