How to use PHP to implement a Dynamic Web server, PHP Dynamic Web server _php Tutorial

Source: Internet
Author: User

How to use PHP to implement a Dynamic Web server, PHP Dynamic Web server


If you are a Web server, you need to know about how the Web server works. Start with a static text server to access the 1.html of the Web server as an example

1. The client sends an HTTP request to the server, and if the server listens on a port number of 9002, then the address on the native test access is http://localhost:9002/1.html.

2. The server listens on port 9002, then after receiving the request request, it can obtain the location of the URI resource in the Web directory from the HTTP head header that needs to be accessed in the request.

3. The server reads the resource files that need to be accessed, and then populates the entities in the HTTP returned to the client.

As follows:

<?phpclass Web_config {//Monitor port number const Port = 9003; Project root directory 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) {//static 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 ";    Processing of static files if (File_exists ($filename)) {return $this->add_header (file_get_contents ($filename));    } else {return $this->not_found (); }}/** * 404 returns * @return String */Private Function Not_found () {$content = "

File not Found

"; return "http/1.1 404 File Not Found\r\ncontent-type:text/html\r\ncontent-length:". strlen ($content). " \r\n\r\n ". $content; }/** * Plus header information * @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::P ort);

As stated in the code above, a static Web server is started as long as the file is executed at the terminal.

For me to access the 1.jpg files in my web directory

The simple static Web server has been completed, the following question is how to let it support the output of dynamic content. Is it necessary to return the resulting results to the client after executing a program inside the Web server? But so the code of the Web server is coupled with the business code, how to solve a Web server, can be used in various business scenarios?

The advent of CGI solves this problem. So what is CGI? The following words are copied:

CGI is an interface standard between an external application (CGI program) and a Web server, and is a discipline for passing information between CGI programs and Web servers. The CGI specification allows the Web server to execute external programs and send their output to a Web browser, CGI turning a simple set of static hypermedia documents from the Web into a complete new interactive media.

Dizzy, for example, for example, we are using the global variable PHP $_server[' query_string ' is the WEB server through the CGI protocol, passed over. For example in Nginx, perhaps you remember such a fastcgi configuration

Fastcgi_param query_string $query _string;

Yes, Nginx passed its global variable $query_string to the FASTCGI_PARAM environment variable.

We also use CGI query_string as a bridge to pass information from the URI of the client request to the CGI program. The query_string is deposited into the environment variable of the request by means of putenv.

We agree that the resources that are accessed in the WEB server are. The CGI suffix means dynamic access, which is a bit like configuring location in Nginx to look for a PHP scripting program. is a rule that checks whether a CGI program should be requested. In order to distinguish it from the WEB server, I wrote a CGI program to query the user's information in C and query the user data according to the user ID.

Approximate access logic, such as

Demo Code Address: https://github.com/zhoumengkang/php/tree/master/php-webserver/dynamic

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

1. Modify the project root directory in config.php web_root

2. Compile the cgi-demo\user.c, compile the command gcc-o user.cgi user.c, and put the user.cgi file under your configured project root directory

3. Execute PHP start.php on the terminal so that the Web server starts the

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

In fact, just on the basis of a static server to do some CGI judgment is the request of forwarding processing, three files on GitHub to merge the code into a file for everyone to watch

<?phpclass Web_config {//Monitor port number const Port = 9003;  Project root directory Const WEB_ROOT = "/users/zhoumengkang/documents/html"; The system supports CGI programs with the file extension 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) {//static get/1.html    http/1.1 ...//dynamic 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);    }//The processing of the static file if (File_exists ($filename)) {return $this->add_header (file_get_contents ($filename));    } else {return $this->not_found ();    }}/** * Set environment variables for CGI programs using * @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); }}/** * Determines whether the requested URI is a legitimate CGI resource * @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 returns * @return String */Private Function Not_found () {$content = "

File not Found

"; return "http/1.1 404 File Not Found\r\ncontent-type:text/html\r\ncontent-length:". strlen ($content). " \r\n\r\n ". $content; }/** * Plus header information * @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::P ort);

The above is the implementation of a Dynamic Web server PHP implementation process, I hope that everyone's learning is helpful.

http://www.bkjia.com/PHPjc/1039198.html www.bkjia.com true http://www.bkjia.com/PHPjc/1039198.html techarticle How to use PHP to implement a Dynamic Web server, PHP Dynamic Web server if a real Web server, then you need to know about how the Web server operating principle. First from the static text ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.