search
HomeBackend DevelopmentPHP Tutorial用 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);
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.