用 PHP 来实现一个动态 Web 服务器
本文所实现的服务器仅仅是演示和理解原理所用,力求简单易懂。有兴趣的朋友可以继续深入改造
要是现实一个 web 服务器,那么就需要大概了解 web 服务器的运行原理。先从静态的文本服务器开始,以访问 web 服务器的1.html为例
1.客户端通过发送一个 http 请求到服务器,如果服务器监听的端口号是9002,那么在本机自身测试访问的地址就是http://localhost:9002/1.html。
2.服务器监听着9002端口,那么在收到请求了请求之后,就能从 http head 头中获取到请求里需要访问的 uri 资源在web 目录中的位置。
3.服务器读取需要访问的资源文件,然后填充到 http 的实体中返回给客户端。
示意图如下:
php<?phpclass 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 的全局变量$_SERVER['QUERY_STRING']就是 Web 服务器通过 CGI 协议之上,传递过来的。例如在 Nginx 中,也许你记得这样的 fastcgi 配置
fastcgi_param QUERY_STRING $query_string;
没错 nginx 把自己的全局变量$query_string传递给了 fastcgi_param 的环境变量中。
下面我们也以 CGI 的QUERY_STRING作为桥梁,将客户端请求的 uri 中的信息传递到 cgi 程序中去。通过putenv的方式把QUERY_STRING存入该请求的环境变量中。
我们约定 Web 服务器中访问的资源是.cgi后缀则表示是动态访问,这一点有点儿类似于 nginx 里配置 location 来寻找 php 脚本程序一样。都是一种检查是否应该请求 cgi 程序的规则。为了和 Web 服务器区别开来,我用 C 写了一个查询用户信息的 cgi 程序,根据用户 id 查询用户资料。
大致的访问逻辑如下图
演示代码地址:https://github.com/zhoumengkang/php/tree/master/php-webserver/dynamic
如果要运行该 demo 需要做如下操作
1.修改config.php里的项目根目录WEB_ROOT
2.编译cgi-demo\user.c,编译命令gcc -o user.cgi user.c,然后将user.cgi文件放入你配置的项目根目录下面
3.在终端执行php start.php ,这样该 web 服务器就启动了
4.通过 http://localhost:9003/user.cgi?id=1 就可以访问看到如下效果了
其实只是在静态服务器的基础上做了一些 cgi 的判断是请求的转发处理,把github 上的三个文件的代码合并到一个文件里方便大家观看
php<?phpclass 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











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.
