PHP实现动态web服务器方法,php动态web服务器
PHP实现动态web服务器方法,php动态web服务器
以下内容通过图文并茂的方式介绍php实现动态web服务器的方法,具体内容如下:
本文所实现的服务器仅仅是演示和理解原理所用,力求简单易懂。有兴趣的朋友可以继续深入改造
要是现实一个 web 服务器,那么就需要大概了解 web 服务器的运行原理。先从静态的文本服务器开始,以访问 web 服务器的1.html为例
1.客户端通过发送一个 http 请求到服务器,如果服务器监听的端口号是9002,那么在本机自身测试访问的地址就是 http://localhost:9002/1.html 。
2.服务器监听着9002端口,那么在收到请求了请求之后,就能从 http head 头中获取到请求里需要访问的 uri 资源在web 目录中的位置。
3.服务器读取需要访问的资源文件,然后填充到 http 的实体中返回给客户端。
示意图如下:
php <?php class web_config { // 监听的端口号 const PORT = 9003; // 项目根目录 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){ // 静态 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"; // 静态文件的处理 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 id="File-Not-Found">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);
代码已经上传 github https://github.com/zhoumengkang/php/tree/master/php-webserver/static
如上代码所述,只要在终端执行该文件,那么一个静态的 web 服务器就启动啦。
下图为我访问我 web 目录下的1.jpg文件的截图
简单的静态 web 服务器已经完成了,下面的问题就是怎么让其支持动态内容的输出了。是不是只需要在 web 服务器内部执行完某个程序之后,把得到的结果返回给客户端就行呢?但是这样 web 服务器的代码就和业务代码耦合在一起了,怎么解决一个 web 服务器,可以运用在各个业务场景下呢?
CGI 的出现解决了这一问题。那么 CGI 是什么呢?下面这段话复制的:
CGI是外部应用程序(CGI程序)与Web服务器之间的接口标准,是在CGI程序和Web服务器之间传递信息的规程。CGI规范允许Web服务器执行外部程序,并将它们的输出发送给Web浏览器,CGI将Web的一组简单的静态超媒体文档变成一个完整的新的交互式媒体。
好晕,举个具体的例子,比如我们在使用的 PHP 的全局变量 <font face="NSimsun">$_SERVER['QUERY_STRING']</font>
就是 Web 服务器通过 CGI 协议之上,传递过来的。例如在 Nginx 中,也许你记得这样的 fastcgi 配置
复制代码 代码如下:
fastcgi_param
QUERY_STRING
$query_string;
没错 nginx 把自己的全局变量 <font face="NSimsun">$query_string</font>
传递给了 fastcgi_param 的环境变量中。
下面我们也以 CGI 的 <font face="NSimsun">QUERY_STRING</font>
作为桥梁,将客户端请求的 uri 中的信息传递到 cgi 程序中去。通过 <font face="NSimsun">putenv</font>
的方式把 <font face="NSimsun">QUERY_STRING</font>
存入该请求的环境变量中。
我们约定 Web 服务器中访问的资源是 <font face="NSimsun">.cgi</font>
后缀则表示是动态访问,这一点有点儿类似于 nginx 里配置 location 来寻找 php 脚本程序一样。都是一种检查是否应该请求 cgi 程序的规则。为了和 Web 服务器区别开来,我用 C 写了一个查询用户信息的 cgi 程序,根据用户 id 查询用户资料。
大致的访问逻辑如下图
演示代码地址: https://github.com/zhoumengkang/php/tree/master/php-webserver/dynamic
如果要运行该 demo 需要做如下操作
1.修改 <font face="NSimsun">config.php</font>
里的项目根目录 <font face="NSimsun">WEB_ROOT</font>
2.编译 <font face="NSimsun">cgi-demo\user.c</font>
,编译命令 <font face="NSimsun">gcc -o user.cgi user.c</font>
,然后将 <font face="NSimsun">user.cgi</font>
文件放入你配置的项目根目录下面
3.在终端执行 <font face="NSimsun">php start.php</font>
,这样该 web 服务器就启动了
4.通过 http://localhost:9003/user.cgi?id=1 就可以访问看到如下效果了
其实只是在静态服务器的基础上做了一些 cgi 的判断是请求的转发处理,把github 上的三个文件的代码合并到一个文件里方便大家观看
php <?php class web_config { // 监听的端口号 const PORT = 9003; // 项目根目录 const WEB_ROOT = "/Users/zhoumengkang/Documents/html"; // 系统支持的 cgi 程序的文件扩展名 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){ // 静态 GET /1.html HTTP/1.1 ... // 动态 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); } // 静态文件的处理 if (file_exists($filename)) { return $this->add_header(file_get_contents($filename)); } else { return $this->not_found(); } } /** * 设置环境变量 给 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); } } /** * 判断请求的 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 id="File-Not-Found">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);
以上就是本文的全部内容,希望大家喜欢。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
