search
HomeBackend DevelopmentPHP TutorialPHP implements dynamic web server method, php dynamic web server_PHP tutorial

PHP implementation of dynamic web server method, php dynamic web server

The following content introduces the method of php to implement dynamic web server through pictures and texts. The specific content is as follows:

The server implemented in this article is only used to demonstrate and understand the principles, and strives to be simple and easy to understand. Friends who are interested can continue the transformation in depth

If you want to implement a web server, you need to have a general understanding of the operating principles of the web server. Let’s start with a static text server, taking accessing 1.html of the web server as an example

1. The client sends an http request to the server. If the port number the server listens to is 9002, then the address to test access on the machine itself is http://localhost:9002 /1.html .

2. The server listens to port 9002. After receiving the request, it can obtain the location in the web directory of the uri resource that needs to be accessed in the request from the http header.

3. The server reads the resource file that needs to be accessed, then fills it into the http entity and returns it to the client.

The schematic diagram is as follows:

php
<&#63;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);

The code has been uploaded to github https://github.com/zhoumengkang/php/tree/master/php-webserver/static

As mentioned in the above code, as long as the file is executed in the terminal, a static web server will be started.

The picture below is a screenshot of me accessing the 1.jpg file in my web directory

The simple static web server has been completed. The next question is how to make it support the output of dynamic content. Do we only need to execute a certain program inside the web server and return the result to the client? But in this way, the web server code is coupled with the business code. How to solve a web server that can be used in various business scenarios?

The advent of CGI solved this problem. So what is CGI? The following paragraph is copied:

CGI is an interface standard between external applications (CGI programs) and Web servers. It is a procedure for transferring information between CGI programs and Web servers. The CGI specification allows Web servers to execute external programs and send their output to Web browsers. CGI turns the Web's set of simple static hypermedia documents into a complete new interactive media.

It’s so confusing. To give a specific example, for example, the global variable <font face="NSimsun">$_SERVER['QUERY_STRING']</font> of PHP we are using is passed by the web server through the CGI protocol. For example, in Nginx, maybe you remember this fastcgi configuration

Copy code The code is as follows:
fastcgi_param
QUERY_STRING
$query_string;

Yes, nginx passes its global variable <font face="NSimsun">$query_string</font> to the environment variable of fastcgi_param.

Below we also use CGI's <font face="NSimsun">QUERY_STRING</font> as a bridge to pass the information in the uri requested by the client to the cgi program. Store <font face="NSimsun">putenv</font> in the environment variable of the request through <font face="NSimsun">QUERY_STRING</font>.

We agree that the resources accessed in the web server are <font face="NSimsun">.cgi</font>. The suffix indicates dynamic access. This is a bit similar to configuring location in nginx to find php scripts. It's all a rule to check whether a cgi program should be requested. In order to distinguish it from the web server, I wrote a cgi program in C to query user information and query user information based on user id.

The general access logic is as follows

Demo code address: https://github.com/zhoumengkang/php/tree/master/php-webserver/dynamic

If you want to run the demo, you need to do the following

1. Modify the project root directory in <font face="NSimsun">config.php</font> <font face="NSimsun">WEB_ROOT</font>

2. Compile <font face="NSimsun">cgi-demouser.c</font>, compile command <font face="NSimsun">gcc -o user.cgi user.c</font>, and then put the <font face="NSimsun">user.cgi</font> file under the root directory of your configured project

3. Execute <font face="NSimsun">php start.php</font> in the terminal, so that the web server will start

4. Through http://localhost:9003/user.cgi?id=1 you can access and see the following effect

其实只是在静态服务器的基础上做了一些 cgi 的判断是请求的转发处理,把github 上的三个文件的代码合并到一个文件里方便大家观看

php
<&#63;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&#63;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,"&#63;")) {
 $uriArr = explode("&#63;", $uri);
 $uri = $uriArr[0];
 $query_string = isset($uriArr[1]) &#63; $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"]) &#63; $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);

以上就是本文的全部内容,希望大家喜欢。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1039195.htmlTechArticlePHP实现动态web服务器方法,php动态web服务器 以下内容通过图文并茂的方式介绍php实现动态web服务器的方法,具体内容如下: 本文所实现的...
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
When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

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.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

What is Content Security Policy (CSP) header and why is it important?What is Content Security Policy (CSP) header and why is it important?Apr 09, 2025 am 12:10 AM

CSP is important because it can prevent XSS attacks and limit resource loading, improving website security. 1.CSP is part of HTTP response headers, limiting malicious behavior through strict policies. 2. The basic usage is to only allow loading resources from the same origin. 3. Advanced usage can set more fine-grained strategies, such as allowing specific domain names to load scripts and styles. 4. Use Content-Security-Policy-Report-Only header to debug and optimize CSP policies.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used?What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used?Apr 09, 2025 am 12:09 AM

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.

What is HTTPS and why is it crucial for web applications?What is HTTPS and why is it crucial for web applications?Apr 09, 2025 am 12:08 AM

HTTPS is a protocol that adds a security layer on the basis of HTTP, which mainly protects user privacy and data security through encrypted data. Its working principles include TLS handshake, certificate verification and encrypted communication. When implementing HTTPS, you need to pay attention to certificate management, performance impact and mixed content issues.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.