Use PHP to process HTTP request messages

HTTP request type

The HTTP protocol defines many types of requests, including OPTIONS, HEAD, GET, POST, PUT, DELETE, TRACE, and CONNECT. The details are as follows:

  • OPTIONS: Returns the HTTP request method supported by the server for a specific resource. You can also test the function of the server by sending a request of'*' to the Web server.

  • HEAD: Ask the server for a response consistent with the GET request, but the response body will not be returned. This method can obtain meta-information not included in the response header without having to transmit the entire response content.

  • GET: Make a request to a specific resource.

  • POST: Submit data to a specific resource for processing request (such as submitting a form or uploading a file). The data is contained in the request body. POST requests may result in the creation of new resources and/or the modification of existing resources.

  • PUT: Upload its latest content to the specified resource location.

  • DELETE: request the server to delete the indicated resource

  • TRACE: echo the request received by the server, mainly used for testing or diagnosis.

  • CONNECT: The HTTP/1.1 protocol is reserved for proxy servers that can change the connection to the pipe mode.

What we commonly use in practical applications is get and post, and other request methods can also be implemented indirectly through get and post.

The difference between GET and POST requests

  • The data submitted by GET is placed in the URL of the HTTP request message. Separate URL and transfer data, and connect parameters with &, such as /Response/get?key1=value1&key2=value2. POST puts the submitted data in the body of the HTTP request message.

  • The size of data submitted by GET is limited, while the data submitted by POST method is not limited.

  • GET needs to use _GET["key"], and POST is implemented by using _POST["key"], reading php://input stream, or reading HTTP_RAW_POST_DATA constant

HTTP Request message structure

The HTTP Request structure is shown in the figure below 
Write picture description here

  • Request Line includes HTTP request type (GET, POST, etc.), request URL, Http version number. 
    When using the "GET" method, the body is empty

  • HTTP Request Header contains HTTP request operation parameters. The header attribute defines various characteristics of the transmitted data.

  • HTTP Request Body contains other information carried in the request

HTTP Request Header

HTTP Request Header contains the following:

  • Cache header

  • Client header field

  • Cookie/Login header field

  • Entity header

  • Miscellaneous 头域

  • Transport header

Cache header

If-Modified-Since

Function: Send the last modification time of the browser-side cached page to the server, and the server will compare this time with the last modification time of the actual file on the server. If the time is the same, return 304, and the client directly uses the local cache file. If the time is inconsistent, it will return 200 and the new file content. After the client receives it, it discards the old file, caches the new file, and displays it in the browser.

For example: If-Modified-Since: Thu, 09 Feb 2012 09:07:57 GMT

If-None-Match

Function: If-None-Match and ETag work together, the working principle is to add ETag information in HTTP Response. When the user requests the resource again, the If-None-Match information (ETag value) will be added to the HTTP Request. If the server verifies that the ETag of the resource has not changed (the resource has not been updated), it will return a 304 status to tell the client to use the local cache file. Otherwise it will return 200 status and new resource and Etag. Using such a mechanism will improve the performance of the website

For example: If-None-Match: “03f2b33c0bfcc1:0”

Pragma

Function: Prevent pages from being cached. In HTTP/1.1 version, it has exactly the same function as Cache-Control: no-cache. 
There is only one usage of Pargma, for example: Pragma: no-cache 
Note: In HTTP/1.0 version, only Pragma is implemented :no-cache, Cache-Control is not implemented

Cache-Control

Role: This is a very important rule. This is used to specify the caching mechanism followed by Response-Request. The meanings of commonly used commands are as follows:

Cache-Control:Public can be cached by any cache 
Cache-Control:Private content is only cached in the private cache 
Cache-Control:no-cache All content will not be cached

Client header field

Accept

Function: The media type that the browser can accept, for example: Accept: text/html means that the browser can accept the type sent back by the server as text/html, which is what we often call html documents. If the server cannot return text/html types Data, the server should return a 406 error (non acceptable).

Wildcard * represents any type

For example, Accept:  /  represents that the browser can handle all types, (generally, the browser sends this to the server)

Accept-Encoding

Function: The browser declares the encoding method it receives, usually specifying the compression method, whether it supports compression, and what compression method it supports (gzip, deflate) (note: this is not just a character encoding);

For example: Accept-Encoding: gzip, deflate

Accept-Language

Function: The browser declares the language it receives. The difference between language and character set: Chinese is a language, and Chinese has multiple character sets, such as big5, gb2312, gbk, etc.;

For example: Accept-Language: en-us

User-Agent

Function: Tell the HTTP server, the name and version of the operating system and browser used by the client.

When we log into forums online, we often see some welcome messages, which list the name and version of your operating system, and the name and version of the browser you are using. This often makes many people feel amazing. In fact, The server application obtains this information from the User-Agent request header field. The User-Agent request header field allows the client to tell the server its operating system, browser, and other attributes.

例如: User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; InfoPath.2; .NET4.0E)

Accept-Charset

Function: The browser declares the character set it receives. This is the various character sets and character encodings introduced earlier in this article, such as gb2312, utf-8 (usually we say that Charset includes the corresponding character encoding scheme)

Cookie/Login header field

Cookie

Function: The most important header, which sends the value of the cookie to the HTTP server

Entity header

Content-Length

Role: The length of the data sent to the HTTP server.

For example: Content-Length: 18

Content-Type

Role: the type of data sent to the HTTP server

例如:Content-Type: application/x-www-form-urlencoded

Miscellaneous 头域

Referer

Function: The server that provides the context information of the request tells the server which link I came from. For example, if I link to a friend from my homepage, his server can count from the HTTP Referer how many users click on my homepage every day Visit his website on the link.

例如: Referer:http://translate.google.cn/?hl=zh-cn&tab=wT

Transport header

Connection

For example: Connection: keep-alive When a web page is opened, the TCP connection used to transmit HTTP data between the client and the server will not be closed. If the client accesses the web page on the server again, it will continue to use the established one. Connection

For example: Connection: close means that after a Request is completed, the TCP connection used to transmit HTTP data between the client and the server will be closed. When the client sends the Request again, the TCP connection needs to be re-established.

Host (this header is required when sending a request)

Function: The request header field is mainly used to specify the Internet host and port number of the requested resource. It is usually extracted from the HTTP URL. 
For example: We enter in the browser: http://www.baidu.com , the browser sends In the request message, it will contain the Host request header domain, as follows: 
Host: http://www.baidu.com

The default port number 80 is used here, if the port number is specified, it becomes: Host: the specified port number

PHP processing Request header

In PHP, if you want to get all HTTP request headers, you can use the getallheaders method, but this method does not exist in any environment. For example, if you use fastcgi to run PHP, there is no such method, so we still We need to consider other methods. Fortunately, $_SERVER has what we want. The key name in it starting with HTTP_ is the HTTP request header:

$headers = array(); 
foreach ($_SERVER as $key => $value) { 
    if ('HTTP_' == substr($key, 0, 5)) { 
        $headers[str_replace('_', '-', substr($key, 5))] = $value; 
        echo "$key: $value\n";
    } 
}1234567

It should be noted that the RFC clearly states that the name of the message header is not case sensitive.

But not all HTTP request headers exist in $_SERVER in the form of keys beginning with HTTP_. For example, Authorization, Content-Length, Content-Type are not like this, so in order to obtain all HTTP request headers, Also need to add the following code:

        // 获取AUTHORIZATION header
        if (isset($_SERVER['PHP_AUTH_DIGEST'])) {            $header['AUTHORIZATION'] = $_SERVER['PHP_AUTH_DIGEST'];            $value = $_SERVER['PHP_AUTH_DIGEST'];            echo "AUTHORIZATION: $value\n";
        } elseif (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {            $header['AUTHORIZATION'] = base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);            $value = base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);            echo "AUTHORIZATION: $value\n";
        }        // 获取CONTENT-LENGTH header
        if (isset($_SERVER['CONTENT_LENGTH'])) {            $header['CONTENT-LENGTH'] = $_SERVER['CONTENT_LENGTH'];            $value = $_SERVER['CONTENT_LENGTH'];            echo "CONTENT-LENGTH: $value\n";
        }        // 获取CONTENT-TYPE header
        if (isset($_SERVER['CONTENT_TYPE'])) {            $header['CONTENT-TYPE'] = $_SERVER['CONTENT_TYPE'];            $value = $_SERVER['CONTENT_TYPE'];            echo "CONTENT-TYPE: $value\n";
        }12345678910111213141516171819202122

PHP handles GET Request parameters

    <?php
    public function request_get(){
        echo $_GET["name"];        echo '<br/>';        echo $_GET["age"];        echo '<br/>';
    }    ?>12345678

Example request: http://host_name/path?name=Peter&age=37

PHP output: 
Peter 
37123

PHP handles POST Request Body

PHP has three ways to process HTTP POST Request body

  • Use _POST["key"] predefined variables

  • Use HTTP_RAW_POST_DATA constant

  • Read php://input stream

_POST[“key”]

_POST["key"] can get the content corresponding to the key by the key value, but can only process the data submitted by Content-Type: application/x-www-form-urlencoded

    <?php
    public function request_post(){        
        echo $_POST["name"];        echo '<br/>';        echo $_POST["age"];        echo '<br/>';
    }    ?>12345678
请求示例 
POST http://host_name/path HTTP/1.1Host: host_name
Content-Length: 18Content-Type: application/x-www-form-urlencodedname=Peter
age=3712345678
PHP output: 
Peter 
37123

HTTP_RAW_POST_DATA

The constant HTTP_RAW_POST_DATA is not available for enctype=”multipart/form-data” form data, which means that the form is not available when submitting binary stream data

HTTP_RAW_POST_DATA and _POST are basically the same, but if the post data is not PHP or something else, you can use GLOBALS['HTTP_RAW_POST_DATA'] to receive it, such as soap/xml.

Therefore, if PHP uses HTTP_RAW_POST_DATA to process post data, you need to add the Content-Type header to the request message when submitting the request. For text, add Content-Type=text/xml

In addition, PHP5.6 has abandoned the constant HTTP_RAW_POST_DATA, and it is recommended to use php://input to process POST data in versions after 5.6.

    <?php
    public function request_post(){
        echo urldecode($GLOBALS['HTTP_RAW_POST_DATA']);
    }    ?>12345
请求示例 
POST http://host_name/path HTTP/1.1Host: host_name
Content-Length: 18Content-Type: text/xmlname=Peter
age=3712345678
PHP output: name=Peterage=37123

php://input

php://input is a read-only stream that can access the raw data of the request, but it is also not available for enctype=”multipart/form-data” form data (same as $HTTP_RAW_POST_DATA).

If PHP uses php://input to process post data, there is no need to add a Content-Type header in the request message

    <?php
    public function request_post(){
        echo file_get_contents('php://input');
    }    ?>12345
请求示例 
POST http://host_name/path HTTP/1.1Host: host_name
Content-Length: 18name=Peter
age=371234567
PHP output: name=Peterage=37123

Through studying the  series of articles about HTTP protocol detailed by Xiaotan, published in the blog garden  , combined with the official PHP documents, I summarized this text about the HTTP protocol. On the way forward, the wisdom of predecessors is needed to indicate the direction, thank you here!

Guess you like

Origin blog.csdn.net/keke795/article/details/112975979