19.07.2023

Post and Get requests, what is the difference between them and which is better and for what purposes? HTTP request types and REST philosophy Get and post http requests


Currently, only two HTTP methods are most commonly used: GET and POST. But it turned out that even among these two "pines" web developers manage to get lost. There is an explanation for this: both methods can be used to obtain the same result. But it must be remembered that the rash use of any of the methods can lead to disastrous consequences, including large loads on the channel and security holes.

To avoid this, it is enough to simply understand in more detail the purposes and differences of these methods.

If you delve into the meaning of the names of the methods, much will become clear. GET (from English to receive), i.e. should be used to request data. POST (c English send by mail) - used to send data to the server. Everything seems to be very simple and clear. But who wants to develop sites a little more complicated than a business card site with one feedback form, it is better to get to know the issue better.

Secure and insecure HTTP requests

The HTTP 1.1 specification introduces two concepts: a secure request and an insecure request, or more specifically, a method.

Safe are methods that can only request information. They cannot change the requested resource, nor can they produce undesirable results for the user, others, or the server. Examples of secure ones are requesting the HTML code of a web page or an image. The safe methods are HEAD and GET.

The note

In reality, craftsmen, of course, can harm GET requests as well. For example, query loops.

Insecure requests, you guessed it, can potentially lead to bad consequences if used repeatedly. Such requests can change the content of the resource being accessed. Examples of such requests: sending messages, registration, online payments. Unsafe methods include POST, PUT, DELETE.

Idempotent methods

Idempotency is the property of methods that, when repeatedly called, will return the same result, except when the information is out of date. This means that when accessing the same URL, all users will see the same web page, image, video, and so on. GET, PUT, DELETE methods have this property.

And now more about the GET and POST methods themselves: let's make a short “summary” for each.

GET

  • designed to receive data from the server;
  • the request body is empty;
  • are processed on the server side faster and with less consumption of server resources due to an empty request body;
  • variables are transferred in the address bar (this is how the user sees it, technically the data is transmitted in the query line) and therefore information about the variables and their values ​​is visible (the data is not protected);
  • capable of passing a small amount of data to the server: there is a limitation on the length of the URL, which depends on the browser, for example, IE6 = 2Kb. Yahoo! developers recommend to focus on this number;
  • can only transmit ASCII characters;
  • such a request can be copied, saved (for example, in bookmarks);
  • the request can be cached (this can be controlled);
  • conditional and partial requests are available to further reduce the load on the channel and the server;
  • does not break the HTTP connection (when the keepAlive mode is enabled on the server).

POST

  • designed to send data to the server;
  • data transfer occurs in the body of the request;
  • server-side processing is slower and "heavier" than GET, because in addition to headers, you need to parse the request body;
  • capable of transferring large amounts of data;
  • able to transfer files;
  • a page generated by the POST method cannot be bookmarked;
  • breaks the HTTP connection;
  • to transfer even a very small amount of information, most browsers send at least two TCP packets: a header, and then a request body.

It turns out that these two methods are not so similar. The use of one or the other should be determined by the task at hand, and not by the fact that GET is used by default or is easier to work with. GET, of course, in most cases is a better option, especially when building fast AJAX, but do not forget about its shortcomings. For myself, I made a simple algorithm-note on the choice of method.

This post is intended to explain how data is transmitted over the Internet using the two main methods: GET and POST. I wrote it as an addition to the instructions for the shift work generator for those who are hardly interested in the details ☺.

Go to the following address (this is for a visual explanation): http://calendarin.net/calendar.php?year=2016 Pay attention to the browser address bar: calendarin.net/calendar.php ?year=2016 The main file is named, followed by a question mark (?) and a "year" parameter with a value of "2016". So, everything that follows the question mark is the GET request. Everything is simple. To pass more than one parameter, they must be separated by an ampersand (&). Example: calendarin.net/calendar.php ?year=2016&display=work-days-and-days-off

The main file is still named, followed by a question mark (?), then a "year" parameter with a value of "2016", then an ampersand (&), then a "display" parameter with a value of "work-days-and-days -off".

GET parameters can be changed directly in the browser's address bar. For example, changing the value "2016" to "2017" and pressing the key will take you to the calendar for 2017.

This is a data transfer in a hidden way (the page address does not change); that is, you can see what was transferred only with the help of a program (script). For example, in the following tool for counting characters in text, the initial data is transmitted by the POST method: http://usefulonlinetools.com/free/character-counter.php

If you have any questions, comments and my E-mail is at your service.

In addition to the GET method, which we discussed in the previous note, there is another method for sending a request via the HTTP protocol - the POST method. The POST method is also very often used in practice.

If, in order to access the server using the GET method, it was enough for us to type a request into the URL, then in the POST method everything works according to a different principle.

In order to perform this kind of request, we need to click on the button with the type="submit" attribute, which is located on the web page. Note that this button is located in the element

, which has the method attribute set to post.

Consider this HTML code:

Enter text:


If the user enters some text into the text field and clicks on the "Submit" button, then the text variable will be sent to the server with the value of the content that the user entered.

POST and GET requests in simple terms

This variable will be sent by the POST method.

If you write in the form like this:

The data will be sent using the GET method.

If, in the case of a GET request, the amount of data that we could transfer was limited by the length of the browser's address bar, then in the case of a POST request, there is no such limit, and we can transfer significant amounts of information.

Another difference between the POST method and the GET method is that the POST method hides all variables and their values ​​passed to them in its body (Entity-Body). In the case of the GET method, they were stored in the request string (Request-URI).

Here is an example of a request made using the POST method:

POST / HTTP/1.0\r\n
Host: www.site.ru\r\n
Referer: http://www.site.ru/index.html\r\n
Cookie: income=1\r\n
Content-Type: application/x-www-form-urlencoded\r\n
Content-Length: 35\r\n
\r\n
login=Dima&password=12345

Thus, when transmitting data using the POST method, it will be much more difficult for an attacker to intercept it, because they are hidden from direct view, so the POST method of transferring data is considered a more secure method.

In addition, using the POST method, you can transfer not only text, but also multimedia data (pictures, audio, video). There is a special Content-Type parameter that specifies the kind of information to be sent.

And finally, in order to get the data that was transmitted by this method on the server, the POST variable is used.

Here is an example of processing in PHP:

echo $_POST['text'];
?>

In the last note, we decided that the browser (client) sends HTTP requests to the server, and the server sends HTTP responses to the client. These requests and responses are made according to certain rules. There is something like syntax, how and in what sequence it should be written. There must be a strictly defined structure.

Let's take a closer look at this structure, which builds requests and responses in the HTTP protocol.

An HTTP request consists of three main parts, which appear in the order listed below. Between the headers and the body of the message there is an empty line (as a separator), it represents the newline character.

Empty string (separator)

Post and Get requests, what is the difference between them and which is better and for what purposes?

message body (Entity Body) – optional parameter

Query string- Specifies the transfer method, the URL to access, and the HTTP protocol version.

Titles– describe the message body, pass various parameters, and other information and information.

message body- this is the data itself that is transmitted in the request. The message body is optional and may be omitted.

When we receive a response request from the server, the body of the message is most often the content of the web page. But, when making requests to the server, it can also sometimes be present, for example, when we transfer the data that we filled out in the feedback form to the server.

In more detail, each element of the request, we will consider in the following notes.

Let's, for example, consider one real request to the server. I highlighted each part of the request with a different color: the query string is green, the headers are orange, and the body of the message is blue.

Browser request:

Host: webgyry.info

Cookie: wp-settings

Connection: keep-alive

In the following example, the message body is already present.

Server response:

Content-Type: text/html; charset=UTF-8

Transfer-Encoding: chunked

Connection: keep-alive

Keep Alive: timeout=5

X-Pingback: //webgyry.info/xmlrpc.php

Document without a title

These are the messages exchanged between the client and the server via the HTTP protocol.

By the way, do you want to know if there is any sense in some element on your site using the "goals" of Yandex Metrics and Google Analytics?

Remove what doesn't work, add what works, and double your revenue.

Yandex Metrica goal setting course.

Google Analytics goal setting course.

The HTTP client sends a request to the server in the form of a request message, which has the following format:

  • Query string (required element)
  • Title (optional element)
  • Empty string (required element)
  • Message body (optional element)

Let's consider each of these elements separately.

Query string

The request string starts with a method token followed by the request URI and protocol version. Elements are separated from each other by spaces:

Let's look at this element in more detail.

Request Method

This element specifies the method to be invoked on the server side at the specified URI.

There are eight methods in HTTP:

  • HEAD
    Used to get the status string and title from the server by URI. Does not change data.
  • GET
    Used to receive data from the server at the specified URI. Does not change data.
  • POST
    Used to send data to the server (such as information about the developer, etc.) using HTML forms.
  • PUT
    Replaces all previous data on the resource with the newly loaded data.
  • DELETE
    Removes all current data on the resource specified by the URI.
  • CONNECT
    Establishes a tunnel connection to the server at the specified URI.
  • OPTIONS
    Describes the connection properties for the specified resource.
  • TRACE
    Provides a message containing a backtrace of the location of the resource specified in the URI.

Request URI

URI (Uniform Resource Identifier) ​​is the identifier of the resource to which the request is sent. The following is the most common URI format:

‘*’ used when the HTTP request is not for a specific resource, but for a server. Used only when the method does not have to be applied to the resource. For example,

absoluteURI used when an HTTP request is made to a proxy. The proxy is requested to pass the request from the available cache and returns a response. For example:

absolute_path | source used most frequently.

Learning to work with GET and POST requests

A specific resource of a specific server is requested. For example, a client wants to get a resource from a server on port 80. The resource address is “www.proselyte.net” and sends the following request:

Request header fields

Header fields allow the client to pass additional information about the request and about itself to the server. These fields act as query modifiers.

Below is a list of the most important header fields that can be used:

  • Accept Charset
  • Accept Encoding
  • Accept-Language
  • Authorization
  • Expect
  • If Match
  • If-Modified-Since
  • If-None-Match
  • If Range
  • If-Unmodified-Since
  • Range
  • Referer
  • User agent

If we want to implement our own client and our own web server, then we can create our own header fields.

HTTP request example

This concludes our study of HTTP requests.
In the next article, we'll look at HTTP responses.

One way to send an HTTP request to a server is to use the GET method. This method is the most common and requests to the server most often occur using it.

The easiest way to create a GET request is to type the URL into the browser's address bar.

The browser will send the following information to the server:

GET/HTTP/1.1
Host: webgyry.info
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Cookie: wp-settings
Connection: keep-alive

The request has two parts:

1. Request Line

2. Headers (Message Headers)

Note that a GET request does not have a message body. But, this does not mean that with its help we cannot transfer any information to the server.

Difference between GET and POST methods

This can be done using special GET parameters.

To add GET parameters to a request, you need to put a "?" at the end of the URL. and after it start asking them according to the following rule:

parameter_name1=parameter_value1& parameter_name2=parameter_value2&…

The separator between the parameters is the "&" sign.

For example, if we want to send two values ​​to the server, the username and age, then this can be done with the following line:

http://site.ru/page.php?name=dima&age=27

When this query is executed, the data gets into the so-called QUERY_STRING environment variable, from which it can be obtained on the server using a server-side web programming language.

Here is an example of how this can be done in PHP.

echo "Your name: " . $_GET["name"] . "
»;
echo "Your age is: " . $_GET["age"] . "
»;
?>

The $_GET["parameter_name"] construct allows you to display the value of the passed parameter.

As a result of executing this code in the browser, you will see:

Your name: dima
Your age: 27

we also make a request to the server using the GET method.

This post is an answer to a question asked in a comment to one of my articles.

In this article, I want to tell you what the GET/POST/PUT/DELETE and other HTTP methods are, what they were invented for and how to use them in accordance with REST.

http

So, what is one of the main protocols of the Internet? I will send pedants to RFC2616, and I will tell the rest in a human way :)

This protocol describes the interaction between two computers (client and server), built on the basis of messages called request (Request) and response (Response). Each message consists of three parts: start line, headers and body. In this case, only the start line is required.

The start lines for the request and the response have a different format - we are only interested in the start line of the request, which looks like this:

METHOD URI http/ VERSION ,

Where METHOD is just the HTTP request method, URI is the resource identifier, VERSION is the protocol version (version 1.1 is currently relevant).

Headers are a set of name-value pairs separated by a colon. Various service information is transmitted in the headers: the message encoding, the name and version of the browser, the address from which the client came (Referrer), and so on.

The body of the message is actually the transmitted data. In the response, the transmitted data, as a rule, is the html page requested by the browser, and in the request, for example, in the body of the message, the contents of the files uploaded to the server are transmitted. But as a rule, there is no message body in the request at all.

HTTP interaction example

Consider an example.

Request:
GET /index.php HTTP/1.1 Host: example.com User-Agent: Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5 Accept: text/html Connection: close
The first line is the query string, the rest are headers; message body missing

Answer:
HTTP/1.0 200 OK Server: nginx/0.6.31 Content-Language: ru Content-Type: text/html; charset=utf-8 Content-Length: 1234 Connection: close ... THE HTML PAGE ITSELF...

Resources and Methods

Let's return to the starting query string and remember that it contains such a parameter as a URI. This stands for Uniform Resource Identifier - a uniform resource identifier. A resource is, as a rule, a file on the server (an example URI in this case is "/styles.css"), but in general, any abstract object can also be a resource ("/blogs/webdev/" - points to the "Web development", and not on a specific file).

The HTTP request type (also called the HTTP method) tells the server what action we want to perform on the resource. Initially (in the early 90s) it was assumed that the client could only want one thing from a resource - to receive it, but now you can create posts, edit a profile, delete messages and much more using the HTTP protocol. And it is difficult to combine these actions with the term "receiving".

To differentiate actions with resources at the level of HTTP methods, the following options were invented:

  • GET - getting a resource
  • POST - resource creation
  • PUT - resource update
  • DELETE - deleting a resource
Pay attention to the fact that the HTTP specification does not oblige the server to understand all methods (which are actually much more than 4) - only GET is required, and also does not indicate to the server what it should do when receiving a request with a particular method. This means that the server, in response to a DELETE /index.php HTTP/1.1 request is not obliged to delete the index.php page on the server, the same as for a GET /index.php HTTP/1.1 request is not obliged to return you the index.php page, he can delete it, for example :)

REST comes into play

REST (REpresentational State Transfer) - this term was introduced in 2000 by Roy Fielding - one of the developers of the HTTP protocol - as the name of a group of principles for building web applications. In general, REST covers a wider area than HTTP - it can be used in other networks with other protocols. REST describes the principles of interaction between the client and the server, based on the concepts of "resource" and "verb" (you can understand them as a subject and a predicate). In the case of HTTP, the resource is defined by its URI, and the verb is the HTTP method.

REST proposes to stop using the same URI for different resources (that is, the addresses of two different articles like /index.php?article_id=10 and /index.php?article_id=20 - this is not a REST way) and use different HTTP methods for different actions. That is, a web application written using the REST approach will delete a resource when it is accessed with the HTTP DELETE method (of course, this does not mean that it is necessary to give the opportunity to delete everything and everyone, but any the application's delete request must use the DELETE HTTP method).

REST gives programmers the ability to write standardized and slightly prettier web applications than ever before. Using REST, the URI for adding a new user will not be /user.php?action=create (GET/POST method), but simply /user.php (strictly POST method).

As a result, by combining the existing HTTP specification and the REST approach, various HTTP methods finally make sense. GET - returns a resource, POST - creates a new one, PUT - updates an existing one, DELETE - deletes it.

Problems?

Yes, there is a small problem with the application of REST in practice. This problem is called HTML.

PUT / DELETE requests can be sent via XMLHttpRequest, by manually contacting the server (say, via curl or even via telnet), but you cannot make an HTML form that sends a full-fledged PUT / DELETE request.

The fact is, the HTML specification does not allow you to create forms that send data other than via GET or POST. Therefore, for normal operation with other methods, it is necessary to imitate them artificially. For example, in Rack (the mechanism on the basis of which Ruby interacts with a web server; Rails, Merb and other Ruby frameworks are made using Rack), you can add a hidden field called "_method" to the form, and specify the name of the method as the value (for example, "PUT") - in this case, a POST request will be sent, but Rack will be able to pretend that it received a PUT, not a POST.

Today I wanted to hit on primitive things a little and describe what can be found on the worldwide web in large quantities and without much difficulty. It's practically about the holy of holies of the HTTP protocol: POST and GET requests.

Many will ask why? I will answer briefly and clearly: not everyone knows what it is and why it is needed, and those who want to know about it (while understanding little about it) often cannot understand what they write in many, many articles on this topic. I will try to explain on my fingers what POST and GET requests are and what they are eaten with.
So, let's start our journey into a fairy tale ...
If you are reading this message, then you at least know what the Internet looks like and what a website is. Having omitted all the subtleties of the work of the World Wide Web, we will operate with such concepts as a user and a site. Like it or not, these two subjects must somehow interact with each other. For example, people communicate with each other through gestures, emotions and speech, animals make some sounds, but what happens when a person and an Internet resource “communicate”? Here we have a case of information exchange, which can be transferred to the human conversation of the "Question and Answer" plan. Moreover, both the user and the site can ask questions and answers. When we talk about a site, its questions and answers, as a rule, are always expressed in the form of a web page with one text or another. When it comes to the user, then everything happens thanks to GET and POST requests (of course, not only, but we are talking about them).

Thus, we found out that the objects of our theme are necessary for "communicating" with the sites. Moreover, both GET and POST requests can be used both for “asking questions” to the site and for “answers”. How are they different? Everything is quite simple. However, to explain the differences, we will have to consider an example, for which we will take the site of the Internet store plan.
You probably often noticed when you were looking for something in online stores that when you searched using filters, the site address turned from the beautiful “http://magaazin.ru” into the terrible “http://magaazin.ru/?category=” shoes&size=38". So, everything that comes after the '?' symbol is your GET request to the site, and to be quite precise, in this case, you kind of ask the site about what it has in the “Shoes” category with sizes “38” (this example is taken from my head, in reality everything may not look so obvious). As a result, we have that we can ask questions ourselves, by indicating them in the address bar of the site. Obviously, this method has several drawbacks. Firstly, anyone who is near the user at the computer can easily peep all the data, so it is highly undesirable to use this type of request to transfer passwords. Secondly, there is a limit on the length of the string that can be transferred from the site address field, which means that a lot of data cannot be transferred. However, the undoubted advantage of using GET requests is its ease of use and the ability to quickly query the site, which is especially useful when developing, but that's another story ...
Now let's talk about POST requests. Savvy readers may have realized that the main difference between this request and its counterpart is the secrecy of the transmitted data. If we consider an online store, then a vivid example where the POST request is used is registration on the site. The site asks for your data, you fill in these data and when you click on the "Registration" button, send your answer. Moreover, this data will not be displayed externally. It is also worth noting that a fairly large amount of information can be requested - and the POST request has no significant restrictions. Well, if you touch on the minus, then you will not quickly generate such a request. Without special skills, this is no longer enough. Although in reality everything is not so difficult, but that again is another story.
Let's sum up a little. POST and GET requests are needed to "communicate" the user and the site. They are practically the opposite of each other. The use of certain types of requests depends on the specific situation and it is extremely inconvenient to use only one type of request.

1. HTTP protocol. Introduction

Just want to clarify one small thing. The terrible word protocol is nothing but an agreement of many people, just at one fine moment people decided: "Let's do it this way, and then everything will be in order." There is nothing to be afraid of, everything is simply outrageous, and we will now open this outrage. So, what is the HTTP protocol and what is it eaten with?

1.1 Client and server

There are no miracles in the world, and even more so in the world of programming and the Internet! Embrace this as an unshakable truth. And, if the program does not work or does not work as you want, then, most likely, it is either not written correctly or contains errors. So, how does the browser ask the server to send it anything? Yes, very easy! You just need to relax a bit and start enjoying the process :-)

1.2. Writing our first HTTP request

If you think that everything is too complicated, then you are mistaken. A person is arranged in such a way that he is simply not able to create something complex, otherwise he himself will get confused in this :-) So, there is a browser and there is a Web server. The initiator of data exchange is always the browser. The web server will never just send anything to anyone so that it sends something to the browser - it is necessary that the browser asks for it. The simplest HTTP request might look like this:


GET http://www.php.net/ HTTP/1.0rnrn


* GET (Translated from English means "get") - the type of request, the type of request can be different, for example POST, HEAD, PUT, DELETE (we will consider some of them below).
* http://www.php.net/ - URI (address) from which we want to get at least some information (of course, we hope to learn an HTML page).
* HTTP/1.0 - the type and version of the protocol that we will use in the process of communicating with the server.
* rn - the end of the line, which must be repeated twice, why, it will become clear a little later.

You can make this request very easily. Run the telnet.exe program, enter www.php.net as the host, specify port 80, and simply type this request by pressing Enter twice as rnrn. In response, you will receive the HTML code of the main page of the site www.php.net.

1.3 Request structure

Let's look at what an HTTP request consists of. Everything is quite simple. Let's start with the fact that an HTTP request is a completely meaningful text. What does it consist of in the general case? We will consider the HTTP 1.0 protocol. So :


Request - Line [ General - Header | Request - Header | Entity - Header ] rn [ Entity - Body ]


* Request-Line - request line
*

Format : "Method Request-URI HTTP-Versionrn"
*Method-
the method by which the Request-URI resource will be processed can be GET, POST, PUT, DELETE, or HEAD.
* Request-URI - relative or absolute link to a page with a set of parameters, for example, /index.html or http://www.myhost.ru/index.html or /index.html?a=1&b=qq. In the latter case, a request will be sent to the server with a set of variables a and b with the corresponding values, and the "&" ampersand character serves as a separator between the parameters.
* HTTP-Version - HTTP protocol version, in our case "HTTP/1.0".

We are extremely interested in the GET and POST processing methods. With the GET method, you can simply pass parameters to the script, and with the POST method, you can emulate submit forms.

For a GET method, the Request-URI might look something like this: "/index.html?param1=1¶m2=2".

* General-Header - the main part of the header.
Format:
Can only have two parameters: Date or Pragma. Date - GMT date in the format "Day of the week, Day Month Year HH:MM:SS GMT", for example, "Tue, 15 Nov 1994 08:12:31 GMT" - the date the request was created. The pragma can have one no-cache value, which disables page caching.

* Request-Header - part of the header describing the request.

Request-Header can have the following parameters : Allow, Authorization, From, If-Modified-Since, Referer, User-Agent.
We won't cover the Autorization parameter in this chapter, as it is used to access private resources, which is not often needed. You can learn how to generate a header for authorized access on your own at www.w3c.org.

* Allow - sets allowed processing methods.
Format: "Allow: GET | HEADn".
The parameter is ignored when specifying the POST processing method in the Request-Line. Specifies the valid request processing methods. Server proxies do not modify the Allow parameter and it reaches the server unchanged.

* From - e-mail address of the sender of the request.
Format: "From:adderssrn".
For example, "From: [email protected]".

* If-Modified-Since - Indicates that the request has not been modified since such-and-such a time.
Format: "If-Modified-Since: datern"
Only used for the GET handler method. The date is specified in GMT in the same format as for the Date parameter in General-Header.

* Referrer - an absolute link to the page from which the request was initiated, i.e. a link to the page from which the user went to ours.
Format: "Referrer: urln".
Example: "Referrer: www.host.ru/index.htmln".
* User-Agent - browser type.
For example: "User-Agent: Mozilla/4.0n"

* Entity-Header - part of the header describing the data of the Entity-Body.
In this part of the request, parameters are set that describe the body of the page. Entity-Header may contain the following parameters: Allow, Content-Encoding, Content-Length, Content-Type, Expires, Last-Modified, extension-header.

* Allow - parameter similar to Allow from General-Header.

* Content-Encoding - Entity-Body data encoding type.
Format: "Content-Encoding: x-gzip | x-compress | other typen".
Example: "Content-Encoding: x-gzipn". Symbol "|" means the word "or", that is, this or that or that, etc.
Another type may indicate how the data is encoded, for example, for the POST method: "Content-Encoding: application/x-www-form-urlencodedn".

* Content-Length - the number of bytes sent to the Entity-Body. The Content-Length value has a completely different meaning for data sent in MIME format, where it acts as a parameter to describe the "external/entity-body" part of the data. Valid integers are zero or more.
Example: "Content-Length: 26457n".

* Content-Type - type of transmitted data.
For example: "Content-Type: text/htmln".

* Expires - The time when the page should be removed from the browser's cache.
Format: "Expires: daten". The date format is similar to the date format for the Date parameter from General-Header.

* Last-Modified - time of the last modification of the sent data.
Format: "Last-Modified: daten". The date format is similar to the date format for the Date parameter from General-Header.

* Extension-header - part of the header, which may be intended, for example, to be processed by the browser, or another program that accepts the document. In this part, you can describe your parameters in the format "ParameterName: parametervaluen". These parameters will be ignored if the client program does not know how to process them.
For example: "Cookie: r=1rn" - sets the well-known cookies for the page.

And now, after such terrible words, let's try to calm down a bit and understand what we need? We will naturally understand by examples.

Let's imagine that we need to get a page from the site by passing Cookies (Cookies), otherwise we will simply be sent as uninvited guests, and moreover, it is known that this page is allowed only after you have visited the main page of the site.

2 GET method

Let's write our request.


GET http :
host: www. site. rurn

Cookie : income = 1rn
rn


This request tells us that we want to get the content of the page at http://www.site.ru/news.html using the GET method. The Host field indicates that this page is located on the www.site.ru server, the Referer field indicates that we came from the main page of the site for news, and the Cookie field indicates that such and such a cookie has been assigned to us. Why are the Host, Referer and Cookie fields so important? Because when creating dynamic sites, normal programmers check these fields that appear in scripts (including PHP) in the form of variables. What is it for? In order, for example, to prevent the site from being robbed, i.e. they didn’t set a program for automatic downloading on it, or so that a person who came to the site would always get to it only from the main page, etc.

Now let's imagine that we need to fill in the form fields on the page and send a request from the form, let this form have two fields: login and password (login and password), and, of course, we know the login and password.


GET http : //www.site.ru/news.html?login=Petya%20Vasechkin&password=qq HTTP/1.0rn
host: www. site. rurn
Referer : http : //www.site.ru/index.htmlrn
Cookie : income = 1rn
rn


Our login is "Petya Vasechkin" Why should we write Petya%20Vasechkin? This is because special characters can be recognized by the server as signs of a new parameter or the end of a request, etc. Therefore, there is an algorithm for encoding parameter names and their values, in order to avoid oshbokovnyh situations in the request. A full description of this algorithm can be found here, and PHP has rawurlencode and rawurldecode functions for encoding and decoding, respectively. I want to note that PHP does the decoding itself if encoded parameters were passed in the request. On this I will conclude the first chapter of acquaintance with the HTTP protocol. In the next chapter, we will look at building POST requests (translated from English - "send"), which will be much more interesting, because. This type of request is used when sending data from HTML forms.

3. POST method.

In the case of an HTTP POST request, there are two options for passing fields from HTML forms, namely using the application/x-www-form-urlencoded and multipart/form-data algorithm. The differences between these algorithms are very significant. The fact is that the algorithm of the first type was created a long time ago, when the HTML language did not yet provide for the possibility of transferring files through HTML forms. So, let's look at these algorithms with examples.

3.1 Content-Type: application/x-www-form-urlencoded.

We write a request similar to our GET request to transfer the login and password, which was considered in the previous chapter:


POST http : //www.site.ru/news.html HTTP/1.0rn
host: www. site. rurn
Referer : http : //www.site.ru/index.htmlrn
Cookie : income = 1rn
Content - Type : application / x - www - form - urlencodedrn
Content - Length : 35rn
rn


Here we see an example of using the Content-Type and Content-Length header fields. Content-Length tells how many bytes the data area will occupy, which is separated from the header by another newline rn. But the parameters that were previously placed in the Request-URI for a GET request are now in the Entity-Body. It can be seen that they are formed in exactly the same way, you just need to write them after the heading. I want to note one more important point, nothing prevents, simultaneously with the set of parameters in the Entity-Body, to put parameters with other names in the Request-URI, for example:


POST http : //www.site.ru/news.html?type=user HTTP/1.0rn
.....
rn
login = Petya % 20Vasechkin & password = qq


3.2 Content-Type: multipart/form-data

As soon as the Internet world realized that it would be nice to send files through forms, the W3C consortium took up the revision of the POST request format. By that time, the MIME format (Multipurpose Internet Mail Extensions - multi-purpose protocol extensions for generating Mail messages) was already widely used, therefore, in order not to reinvent the wheel, we decided to use part of this message format to create POST requests in the HTTP protocol.

What are the main differences between this format and the application/x-www-form-urlencoded type?

The main difference is that the Entity-Body can now be divided into sections that are separated by boundaries (boundary). What is most interesting is that each section can have its own title to describe the data that is stored in it, i.e. in one request, you can transfer data of various types (as in a Mail letter, you can transfer files along with the text).

So let's get started. Consider again the same example with the transfer of login and password, but now in a new format.


POST http : //www.site.ru/news.html HTTP/1.0rn
host: www. site. rurn
Referer : http : //www.site.ru/index.htmlrn
Cookie : income = 1rn

Content - Length : 209rn
rn
-- 1BEF0A57BE110FD467Arn
Content-Disposition: form-data; name = "login" rn
rn
Petya Vasechkinrn
-- 1BEF0A57BE110FD467Arn
Content-Disposition: form-data; name="password"rn
rn
qqrn
-- 1BEF0A57BE110FD467A -- rn


Now let's understand what is written. :-) I bolded some of the rn characters on purpose so they don't blend into the data. Looking closely, you can see the boundary field after the Content-Type. This field specifies the section separator - the boundary. As a border, a string consisting of Latin letters and numbers, as well as some other characters (unfortunately, I don’t remember which ones) can be used. In the body of the request, "--" is added to the beginning of the boundary, and the request ends with a boundary, to which the characters "--" are also added to the end. Our request has two sections, the first describes the login field, and the second describes the password field. Content-Disposition (data type in the section) says that this will be data from the form, and the field name is set to the name of the field. This ends the section header and is followed by the section data area, which contains the field value (no encoding of the value required!).

I want to draw your attention to the fact that in the section headers you do not need to use Content-Length, but in the request header you need and its value is the size of the entire Entity-Body after the second rn following the Content-Length: 209rn. Those. Entity-Body is separated from the header by an additional newline (which can also be seen in sections).

Now let's write a request to transfer the file.


POST http : //www.site.ru/postnews.html HTTP/1.0rn
host: www. site. rurn
Referer: http: //www.site.ru/news.htmlrn
Cookie : income = 1rn
Content - Type : multipart / form - data ; boundary = 1BEF0A57BE110FD467Arn
Content - Length : 491rn
rn
-- 1BEF0A57BE110FD467Arn
Content-Disposition: form-data; name = "news_header" rn
rn
News examplern
-- 1BEF0A57BE110FD467Arn
Content-Disposition: form-data; name = "news_file" ; filename="news.txt" rn
Content - Type : application / octet - streamrn
Content - Transfer - Encoding : binaryrn
rn
And here's the news, which is in the news file. txtrn
-- 1BEF0A57BE110FD467A -- rn


In this example, the first section sends the headline of the news, and the second section sends the file news.txt. The attentive one will see the filename and Content-Type fields in the second section. The filename field specifies the name of the file being uploaded, and the Content-Type field specifies the type of the file. Application/octet-stream indicates that this is a standard data stream, and Content-Transfer-Encoding: binary indicates that this is binary data, not encoded in anything.

A very important point. Most CGI scripts are written by smart people, so they like to check the type of the incoming file, which is in Content-Type. For what? Most often, downloading files on sites is used to receive pictures from a visitor. So, the browser itself tries to determine what kind of file the visitor wants to send and inserts the appropriate Content-Type into the request. The script checks it upon receipt, and, for example, if it is not a gif or jpeg, it ignores this file. Therefore, when "manually" generating a request, take care of the Content-Type value so that it is closest to the format of the file being transferred.

Image/gif for gif
image/jpeg for jpegs
image/png for png
image/tiff for tiff (which is rarely used, it's a very capacious format)

In our example, a request is formed in which a text file is transmitted. Similarly, a request is formed to transfer a binary file.

4. Postscript.

I think that it is not worth talking about sending requests to the server in detail. This is purely a matter of PHP technology :-). It is enough to carefully read the section on socket functions, or on the functions of the CURL module in the official PHP documentation.

From the above, I hope it is now clear why the question is: "How do I form a POST request using the header function?" - meaningless. The header(string) function adds an entry only to the request header, not to the request body.

Back

2023
maccase.ru - Android. Brands. Iron. News