如何用PHP來實(shí)現(xiàn)一個(gè)動(dòng)態(tài)Web服務(wù)器
要是現(xiàn)實(shí)一個(gè) web 服務(wù)器,那么就需要大概了解 web 服務(wù)器的運(yùn)行原理。先從靜態(tài)的文本服務(wù)器開始,以訪問 web 服務(wù)器的1.html為例
1.客戶端通過發(fā)送一個(gè) http 請(qǐng)求到服務(wù)器,如果服務(wù)器監(jiān)聽的端口號(hào)是9002,那么在本機(jī)自身測(cè)試訪問的地址就是http://localhost:9002/1.html。
2.服務(wù)器監(jiān)聽著9002端口,那么在收到請(qǐng)求了請(qǐng)求之后,就能從 http head 頭中獲取到請(qǐng)求里需要訪問的 uri 資源在web 目錄中的位置。
3.服務(wù)器讀取需要訪問的資源文件,然后填充到 http 的實(shí)體中返回給客戶端。
示意圖如下:
<?php class web_config { // 監(jiān)聽的端口號(hào) const PORT = 9003; // 項(xiàng)目根目錄 const WEB_ROOT = "/Users/zhoumengkang/Documents/html"; } class server { private $ip; private $port; public function __construct($ip, $port) { $this->ip = $ip; $this->port = $port; $this->await(); } private function await() { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($sock < 0) { echo "Error:" . socket_strerror(socket_last_error()) . "\n"; } $ret = socket_bind($sock, $this->ip, $this->port); if (!$ret) { echo "BIND FAILED:" . socket_strerror(socket_last_error()) . "\n"; exit; } echo "OK\n"; $ret = socket_listen($sock); if ($ret < 0) { echo "LISTEN FAILED:" . socket_strerror(socket_last_error()) . "\n"; } do { $new_sock = null; try { $new_sock = socket_accept($sock); } catch (Exception $e) { echo $e->getMessage(); echo "ACCEPT FAILED:" . socket_strerror(socket_last_error()) . "\n"; } try { $request_string = socket_read($new_sock, 1024); $response = $this->output($request_string); socket_write($new_sock, $response); socket_close($new_sock); } catch (Exception $e) { echo $e->getMessage(); echo "READ FAILED:" . socket_strerror(socket_last_error()) . "\n"; } } while (TRUE); } /** * @param $request_string * @return string */ private function output($request_string){ // 靜態(tài) GET /1.html HTTP/1.1 ... $request_array = explode(" ",$request_string); if(count($request_array) < 2){ return $this->not_found(); } $uri = $request_array[1]; $filename = web_config::WEB_ROOT . $uri; echo "request:".$filename."\n"; // 靜態(tài)文件的處理 if (file_exists($filename)) { return $this->add_header(file_get_contents($filename)); } else { return $this->not_found(); } } /** * 404 返回 * @return string */ private function not_found(){ $content = " <h1>File Not Found </h1> "; return "HTTP/1.1 404 File Not Found\r\nContent-Type: text/html\r\nContent-Length: ".strlen($content)."\r\n\r\n".$content; } /** * 加上頭信息 * @param $string * @return string */ private function add_header($string){ return "HTTP/1.1 200 OK\r\nContent-Length: ".strlen($string)."\r\nServer: mengkang\r\n\r\n".$string; } } $server = new server("127.0.0.1", web_config::PORT);
如上代碼所述,只要在終端執(zhí)行該文件,那么一個(gè)靜態(tài)的 web 服務(wù)器就啟動(dòng)啦。
下圖為我訪問我 web 目錄下的1.jpg文件的截圖
簡(jiǎn)單的靜態(tài) web 服務(wù)器已經(jīng)完成了,下面的問題就是怎么讓其支持動(dòng)態(tài)內(nèi)容的輸出了。是不是只需要在 web 服務(wù)器內(nèi)部執(zhí)行完某個(gè)程序之后,把得到的結(jié)果返回給客戶端就行呢?但是這樣 web 服務(wù)器的代碼就和業(yè)務(wù)代碼耦合在一起了,怎么解決一個(gè) web 服務(wù)器,可以運(yùn)用在各個(gè)業(yè)務(wù)場(chǎng)景下呢?
CGI 的出現(xiàn)解決了這一問題。那么 CGI 是什么呢?下面這段話復(fù)制的:
CGI是外部應(yīng)用程序(CGI程序)與Web服務(wù)器之間的接口標(biāo)準(zhǔn),是在CGI程序和Web服務(wù)器之間傳遞信息的規(guī)程。CGI規(guī)范允許Web服務(wù)器執(zhí)行外部程序,并將它們的輸出發(fā)送給Web瀏覽器,CGI將Web的一組簡(jiǎn)單的靜態(tài)超媒體文檔變成一個(gè)完整的新的交互式媒體。
好暈,舉個(gè)具體的例子,比如我們?cè)谑褂玫?PHP 的全局變量$_SERVER['QUERY_STRING']就是 Web 服務(wù)器通過 CGI 協(xié)議之上,傳遞過來的。例如在 Nginx 中,也許你記得這樣的 fastcgi 配置
fastcgi_param QUERY_STRING $query_string;
沒錯(cuò) nginx 把自己的全局變量$query_string傳遞給了 fastcgi_param 的環(huán)境變量中。
下面我們也以CGI的QUERY_STRING作為橋梁,將客戶端請(qǐng)求的 uri 中的信息傳遞到 cgi 程序中去。通過putenv的方式把QUERY_STRING存入該請(qǐng)求的環(huán)境變量中。
我們約定 Web 服務(wù)器中訪問的資源是.cgi后綴則表示是動(dòng)態(tài)訪問,這一點(diǎn)有點(diǎn)兒類似于 nginx 里配置 location 來尋找 php 腳本程序一樣。都是一種檢查是否應(yīng)該請(qǐng)求 cgi 程序的規(guī)則。為了和 Web 服務(wù)器區(qū)別開來,我用 C 寫了一個(gè)查詢用戶信息的 cgi 程序,根據(jù)用戶 id 查詢用戶資料。
大致的訪問邏輯如下圖
演示代碼地址:https://github.com/zhoumengkang/php/tree/master/php-webserver/dynamic
如果要運(yùn)行該 demo 需要做如下操作
1.修改config.php里的項(xiàng)目根目錄WEB_ROOT
2.編譯cgi-demo\user.c,編譯命令gcc -o user.cgi user.c,然后將user.cgi文件放入你配置的項(xiàng)目根目錄下面
3.在終端執(zhí)行php start.php ,這樣該 web 服務(wù)器就啟動(dòng)了
4.通過 http://localhost:9003/user.cgi?id=1 就可以訪問看到如下效果了
其實(shí)只是在靜態(tài)服務(wù)器的基礎(chǔ)上做了一些 cgi 的判斷是請(qǐng)求的轉(zhuǎn)發(fā)處理,把github 上的三個(gè)文件的代碼合并到一個(gè)文件里方便大家觀看
<?php class web_config { // 監(jiān)聽的端口號(hào) const PORT = 9003; // 項(xiàng)目根目錄 const WEB_ROOT = "/Users/zhoumengkang/Documents/html"; // 系統(tǒng)支持的 cgi 程序的文件擴(kuò)展名 const CGI_EXTENSION = "cgi"; } class server { private $ip; private $port; public function __construct($ip, $port) { $this->ip = $ip; $this->port = $port; $this->await(); } private function await() { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($sock < 0) { echo "Error:" . socket_strerror(socket_last_error()) . "\n"; } $ret = socket_bind($sock, $this->ip, $this->port); if (!$ret) { echo "BIND FAILED:" . socket_strerror(socket_last_error()) . "\n"; exit; } echo "OK\n"; $ret = socket_listen($sock); if ($ret < 0) { echo "LISTEN FAILED:" . socket_strerror(socket_last_error()) . "\n"; } do { $new_sock = null; try { $new_sock = socket_accept($sock); } catch (Exception $e) { echo $e->getMessage(); echo "ACCEPT FAILED:" . socket_strerror(socket_last_error()) . "\n"; } try { $request_string = socket_read($new_sock, 1024); $response = $this->output($request_string); socket_write($new_sock, $response); socket_close($new_sock); } catch (Exception $e) { echo $e->getMessage(); echo "READ FAILED:" . socket_strerror(socket_last_error()) . "\n"; } } while (TRUE); } /** * @param $request_string * @return string */ private function output($request_string){ // 靜態(tài) GET /1.html HTTP/1.1 ... // 動(dòng)態(tài) GET /user.cgi?id=1 HTTP/1.1 ... $request_array = explode(" ",$request_string); if(count($request_array) < 2){ return ""; } $uri = $request_array[1]; echo "request:".web_config::WEB_ROOT . $uri."\n"; $query_string = null; if ($uri == "/favicon.ico") { return ""; } if (strpos($uri,"?")) { $uriArr = explode("?", $uri); $uri = $uriArr[0]; $query_string = isset($uriArr[1]) ? $uriArr[1] : null; } $filename = web_config::WEB_ROOT . $uri; if ($this->cgi_check($uri)) { $this->set_env($query_string); $handle = popen(web_config::WEB_ROOT.$uri, "r"); $read = stream_get_contents($handle); pclose($handle); return $this->add_header($read); } // 靜態(tài)文件的處理 if (file_exists($filename)) { return $this->add_header(file_get_contents($filename)); } else { return $this->not_found(); } } /** * 設(shè)置環(huán)境變量 給 cgi 程序使用 * @param $query_string * @return bool */ private function set_env($query_string){ if($query_string == null){ return false; } if (strpos($query_string, "=")) { putenv("QUERY_STRING=".$query_string); } } /** * 判斷請(qǐng)求的 uri 是否是合法的 cgi 資源 * @param $uri * @return bool */ private function cgi_check($uri){ $info = pathinfo($uri); $extension = isset($info["extension"]) ? $info["extension"] : null; if( $extension && in_array($extension,explode(",",web_config::CGI_EXTENSION))){ return true; } return false; } /** * 404 返回 * @return string */ private function not_found(){ $content = "<h1>File Not Found </h1>"; return "HTTP/1.1 404 File Not Found\r\nContent-Type: text/html\r\nContent-Length: ".strlen($content)."\r\n\r\n".$content; } /** * 加上頭信息 * @param $string * @return string */ private function add_header($string){ return "HTTP/1.1 200 OK\r\nContent-Length: ".strlen($string)."\r\nServer: mengkang\r\n\r\n".$string; } } $server = new server("127.0.0.1", web_config::PORT);
以上就是PHP實(shí)現(xiàn)一個(gè)動(dòng)態(tài)Web服務(wù)器的全部實(shí)現(xiàn)過程,希望對(duì)大家的學(xué)習(xí)有所幫助。
- asp.net MaxLengthValidator 最大長(zhǎng)度驗(yàn)證控件代碼
- 基于jquery實(shí)現(xiàn)的服務(wù)器驗(yàn)證控件的啟用和禁用代碼
- ASP.net的驗(yàn)證控件淺析
- python批量同步web服務(wù)器代碼核心程序
- Python基于twisted實(shí)現(xiàn)簡(jiǎn)單的web服務(wù)器
- Go語言實(shí)現(xiàn)簡(jiǎn)單的一個(gè)靜態(tài)WEB服務(wù)器
- ASP.NET自定義Web服務(wù)器控件之Button控件
- 使用C++制作簡(jiǎn)單的web服務(wù)器(續(xù))
- PHP實(shí)現(xiàn)動(dòng)態(tài)web服務(wù)器方法
- ASP.NET中驗(yàn)證控件的使用方法
- ASP.NETWeb服務(wù)器驗(yàn)證控件如何使用
相關(guān)文章
Zend Framework教程之模型Model基本規(guī)則和使用方法
這篇文章主要介紹了Zend Framework教程之模型Model基本規(guī)則和使用方法,結(jié)合實(shí)例形式詳細(xì)分析了Zend Framework中模型的原理與具體使用技巧,需要的朋友可以參考下2016-03-03vmware linux系統(tǒng)安裝最新的php7圖解
在本篇文章中我們給大家分享了關(guān)于vmware linux系統(tǒng)安裝最新的php7的相關(guān)知識(shí)點(diǎn)內(nèi)容,需要的朋友們學(xué)習(xí)下。2019-04-04Thinkphp 框架基礎(chǔ)之入口文件功能、定義與用法分析
這篇文章主要介紹了Thinkphp 框架基礎(chǔ)之入口文件功能、定義與用法,結(jié)合實(shí)例形式分析了Thinkphp入口文件基本功能、原理、定義與操作注意事項(xiàng),需要的朋友可以參考下2020-04-04超詳細(xì)的php用戶注冊(cè)頁面填寫信息完整實(shí)例(附源碼)
這篇文章主要介紹了一個(gè)超詳細(xì)的php用戶注冊(cè)頁面填寫信息完整實(shí)例,內(nèi)容包括郵箱自動(dòng)匹配、密碼強(qiáng)度驗(yàn)證以及防止表單重復(fù)等,小編特別喜歡這篇文章,推薦給大家。2015-11-11destoon實(shí)現(xiàn)公司新聞詳細(xì)頁添加評(píng)論功能的方法
這篇文章主要介紹了destoon實(shí)現(xiàn)公司新聞詳細(xì)頁添加評(píng)論功能的方法,需要的朋友可以參考下2014-07-07實(shí)例分析PHP將字符串轉(zhuǎn)換成數(shù)字的方法
在本篇文章里我們給大家分享的是關(guān)于PHP將字符串轉(zhuǎn)換成數(shù)字的方法和相關(guān)知識(shí)點(diǎn),有興趣的朋友們學(xué)習(xí)下。2019-01-01用Php編寫注冊(cè)后Email激活驗(yàn)證的實(shí)例代碼
通過使用Email驗(yàn)證激活的方法,可以有效的幫你阻止惡意的Spam和注冊(cè)機(jī)器人的訪問。 用php編寫注冊(cè)后Email驗(yàn)證激活的步驟非常簡(jiǎn)單,相信幾分鐘之內(nèi)你就能學(xué)會(huì)。2013-03-03