內建Web Server
CLI SAPI 提供了一個內建的Web伺服器。
這個內建的Web伺服器主要用於本地開發使用,不可用於線上產品環境。
URI請求會被髮送到PHP所在的的工作目錄(Working Directory)進行處理,除非你使用了-t參數來自定義不同的目錄。
如果請求未指定執行哪個PHP檔案,則預設執行目錄內的index.php 或者 index.html。如果這兩個檔案都不存在,伺服器會返回404錯誤。
當你在命令列啟動這個Web Server時,如果指定了一個PHP檔案,則這個檔案會作為一個「路由」指令碼,意味著每次請求都會先執行這個指令碼。如果這個指令碼返回 false
,那麼直接返回請求的檔案(例如請求靜態檔案不作任何處理)。否則會把輸出返回到瀏覽器。
示例 #1 啟動Web伺服器
$ 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
執行之後終端顯示:
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.