天天看點

php建立伺服器,利用 PHP 快速建立一個 Web 伺服器

從 PHP 5.4.0 起, CLI SAPI 提供了一個内置的 Web 伺服器。我們可以通過這個内置的 Web 伺服器很友善的搭建一個本地開發環境。

啟動 Web 伺服器

預設情況下,URI 請求會被發送到 PHP 所在的的工作目錄進行處理。$cd/tmp/wordpress-install$php-Slocalhost:8000PHP7.1.16DevelopmentServerstartedatMonJun416:48:422018Listeningonhttp://localhost:8000Documentrootis/private/tmp/wordpress-installPressCtrl-Ctoquit.如果請求未指定執行 PHP 檔案,則預設執行目錄内的index.php或者index.html。如果這兩個檔案都不存在,伺服器會則傳回 404 錯誤。

接着通過浏覽器打開http://localhost:8000/就可通路對應的 Web 程式,在終端視窗會輸出類似以下的通路日志:[MonJun416:50:552018]::1:54854[302]:/[MonJun416:50:552018]::1:54855[200]:/wp-admin/setup-config.php[MonJun416:50:552018]::1:54858[200]:/wp-includes/css/buttons.min.css?ver=4.9.4[MonJun416:50:552018]::1:54860[200]:/wp-includes/js/jquery/jquery.js?ver=1.12.4[MonJun416:50:552018]::1:54859[200]:/wp-admin/css/install.min.css?ver=4.9.4[MonJun416:50:552018]::1:54861[200]:/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1[MonJun416:50:552018]::1:54862[200]:/wp-admin/js/language-chooser.min.js?ver=4.9.4[MonJun416:50:562018]::1:54863[200]:/wp-admin/images/wordpress-logo.svg?ver=20131107[MonJun416:50:572018]::1:54864[404]:/favicon.ico-Nosuchfileordirectory

啟動時指定根目錄

如果要自定義啟動根目錄,你可以使用-t參數來自定義不同的目錄。$cd/tmp/wordpress-install$php-Slocalhost:8000-twp-admin/PHP7.1.16DevelopmentServerstartedatMonJun416:53:552018Listeningonhttp://localhost:8000Documentrootis/private/tmp/wordpress-install/wp-adminPressCtrl-Ctoquit.[MonJun416:54:042018]::1:54912[302]:/

使用路由腳本

預設情況下,PHP 建立的 Web 伺服器會由index.php接收所有請求參數。如果要讓指定的 PHP 檔案來處理請求,可以在啟動這個 Web 伺服器時直接指定要處理請求的檔案名。這個檔案會作為一個路由腳本,意味着每次請求都會先執行這個腳本。(通常将此檔案命名為 router.php)

下面我們來看一個例子,請求圖檔直接顯示圖檔,請求 HTML 則顯示 “Welcome to PHP”。$vimrouter.php<?php //router.phpif(preg_match('/\.(?:png|jpg|jpeg|gif)$/',$_SERVER["REQUEST_URI"]))returnfalse;//直接傳回請求的檔案else{echo"

WelcometoPHP

";}?>

執行後,通路 HTML 檔案就會在終端視窗輸出對應的 HTML 代碼。$php-Slocalhost:8000router.phpPHP7.1.16DevelopmentServerstartedatMonJun417:00:192018Listeningonhttp://localhost:8000Documentrootis/private/tmp/wordpress-installPressCtrl-Ctoquit.$curlhttp://localhost:8000/index.html

WelcometoPHP

%

接下來,我們在看看通路圖檔。通路圖檔後就會在終端視窗輸出類似以下的通路日志:[MonJun417:00:392018]::1:55008[200]:/wp-content/themes/twentyseventeen/assets/images/coffee.jpg[MonJun417:00:572018]::1:55034[200]:/wp-content/themes/twentyseventeen/assets/images/espresso.jpg[MonJun417:01:082018]::1:55035[200]:/wp-content/themes/twentyseventeen/assets/images/header.jpg[MonJun417:01:162018]::1:55037[200]:/wp-content/themes/twentyseventeen/assets/images/sandwich.jpg

今日思想

不能忍受生命中注定要忍受的事情,就是軟弱和愚蠢的表現。

——勃朗特