the Internet Windows Android

POST and GET requests with simple words. How to send POST Request Browser: Method Post Variable Post in PHP Use Examples

In this lesson, we consider receiving data transmission between forms and pages. These methods are POST and GET. We will talk about each other separately and in more detail. Generally speaking, it is necessary for communication between forms. For example, we fill out some fields on the page and we need to transfer them to another page for processing.

GET method in PHP

To begin with, we will analyze the GET method. This is when all variables and their values \u200b\u200bare transmitted directly through the address. Now you will see everything on the example, and even understand how most sites and forums work.
For example, we have an HTML page of this type:

Page with an example of transmitting variables using Get link

See the link? It is complicated and consists of several parts. Let's wonder everything around the shelves:
https: // Site - The address of the domain or, as it is also called, Host.
index.php. - PHP page that will process the request.
? - The separation symbol between the address and block with variables.
Next are variables and their values \u200b\u200bthat are separated by the symbol. & .
name \u003d Sergey - Name variable and its SERGEY value.
age \u003d 22. - The same, variable AGE, value 22.

All disassembled, now let's see how it is processed in PHP, using the GET method.
Page index.php, as you remember, we passed to her:

To begin with, advice: always check the variables on the correctness: on the void, for compliance with the valid values \u200b\u200band so on. Since everything is transmitted via the address bar, the data can be easily replaced and hurt the site. Now according to the code itself: we, with help, checked the variables of the name and age to the emptiness and, if they are not empty, then brought them off, and if empty, then simply reported it.
Everything is simple, agree? For example, you can create an HTML page and make links through variables in the index.php to index.php and display this or that page depending on the resulting value. Well, we will talk about it later, in the article about creating a website on PHP from scratch. To miss anything, I advise you to subscribe to RSS.

PHP PHP method

To demonstrate the work of this method, we will need a little more than a simple line with the address :) It will be necessary to create an HTML page with a filling form, but nothing, I will give a ready-made example for you:

Page with an example of transmitting variables using POST

Fill the fields for transferring information:

Specify your name:

Specify your age:

So, we have created an HTML page with a simple form. Remember, the POST method can only be used in the form.
The first form parameter is "Method", it defines the method that we will use for transmission. As you could guess, it is either GET or POST. In this case, if GET is installed, then all the names of the fields (in the form of variable names), as well as their values \u200b\u200bare transmitted by reference, as in the section about the GET method. If POST is set, then all the names of variables and values \u200b\u200bwill be transmitted as a browser request to a web server. That is, they will not be visible in the address bar. In many cases, this is very useful. Also, POST is safer, it is also clear, because the variables with their values \u200b\u200bare no longer so easy to edit, although it is also possible.

The second parameter of the form is "Action". This is the path and name of the script file to which we transmit data. In our case, this is index.php. This path can be transmitted and completely, that is, so: action \u003d "https://my_site.ru/index.php". If you do not specify the value of the "Action" parameter, then all information will be transmitted to the main script, that is, the index.php index page of your site, which is quite logical.

Now we get data from our form. Once we passed in index.php, it means that the code will be the code of this page:

"; Echo" Name - "; echo $ _post [" user_name "]; echo"
age - "; Echo $ _Post [" Age "]; echo" years ";) ELSE (ECHO" Variables did not reach. Check all times. ";)?\u003e

Do not forget to check for emptiness and permissible values. Next, you need to clarify why our variables are called the User_Name and Age? And you look at the shape fields that we created above. See there iNPUT NAME \u003d "User_Name" Type \u003d "Text" ? Here is the NAME parameter and sets the name of the variable that we get with this field. The same with AGE. I hope it is clear. Well, the acquisition of the variable and its values \u200b\u200bvia POST is almost no different from the GET, which we considered above.

Well, the lesson turned out to be big, but one of the most useful, because the transfer of variables between forms and pages is exactly the interactivity for which we use PHP.

You could notice that the addresses can be contemplated on most sites:

Http: //syt/index.php? Blog \u003d 2

Here, not even knowing PHP, you can guess that we appeal to the file index.php. But what goes after the question of the question, few people know. Everything is quite simple: ? blog \u003d 2 This is an announcement of the global variable "$ _Get [" Blog "]" with the value "2". Thus, I transmit a variable to the script that is responsible for output from the database. Let's write a small script in which you will only clearly see:

if (isset ($ _ get ["blog"])) (
echo $ _get ["blog"];
}
?>

We use the IF () condition operator () as a condition worth this line:

Isset ($ _ get ["blog"])

isset () Allows you to find out if there is a variable that is listed in brackets, that is, the condition that I described in the code sounds like this: if there is a variable $ _Get ["blog"] then output the contents of this variable on the screen. That's what happened:

I think the global variable is clearly created. $ _Get. with the identifier that we have announced in the address bar ( in this case, with the "Blog" identifier)

Now I want to clarify one moment. Suppose we need to declare two variables, how to do it? The first variable is declared after the question of the question "?" The second variable is declared after such a sign "&" ( To be honest I do not know what kind of sign ), here is an example announcement of three variables:

Http: //syt/index.php? A \u003d 1 & b \u003d 2 & c \u003d 3

Here is the output code:

if (ISset ($ _ get ["a"]) and isset ($ _ get ["b"]) and isset ($ _ get ["C"])) (
Echo $ _GET ["A"]. "
";
Echo $ _get ["b"]. "
";
Echo $ _Get ["C"]. "
";
}
?>

The condition sounds like this:

If there is a global variable $ _GET ["A"] and the global variable $ _Get ["b"] and the global variable $ _Get ["C"] then output them on the screen, Here is the result:

Forms

Before we go to pOST. Requests, you need to disassemble what form are? Why do you need? Because the global variable $ _post ["] is created through forms. What is a form? These are fields to enter any information of the user. Fields are in one line, large fields, there are radio buttons, check boxes. We will analyze everything in order ...

Form is a tag:


Elements of form

The form has attributes, list the most common:

Let's create a form:


Elements of form

I set the file as a handler file test.php. Since it is in it that I am writing examples for you. I put the POST method as it is these methods that use in 99.9% of cases. I also assigned our form name - Form

Now plunge into the world of form elements. First of all, you must understand that almost all elements are tag Difference only in the attribute type These tags. Let me list the forms you used:

I am sure that you have not met such fields, so here as it says: "no comments"

Now let's make a small training questionnaire with which we will work further. Our task is to make a small form that tells us the name of the fill, the floor, from what country it is, favorite color and field of text where the user can add something about himself. That's what I did:

Your last name name Patronymic:

Your gender:
M.
J.

What country are you from



Favorite color (a):

The black:
Red:
White:
Other:

About myself:




Please note that almost every tag has an attribute valueWhat is he? It records the data you are going to transfer to another page. I hope it is clear

Now if you run this code in the browser, we will see the following:

Form I used an attribute action. with meaning test.php. This means how I have already said that the data from the form is sent to the Test.php file.

POST request

Now write php code which will allow us to see the information you entered. Where is the data stored? In the case of the GET request, our data was lying in the $ _get global variable]. With a post request, the data will lie in the global variable $ _post ["]. In square brackets, it is necessary to prescribe, as in the case of the GET global variable, an identifier. The question is where this identifier take? That's why NAME attribute is needed at the form elements! It is these names that serve us with the key in the global array of POST. Well, let's start the script description:

if (ISset ($ _ post ["submit"])) (
Echo "FULL NAME:" $ _ POST ["FIO"]. "
";
Echo "Gender:" $ _ POST ["SEX"]. "
";
Echo "Country of residence:" $ _ post ["City"]. "
";

Echo "Favorite color (a):
";
Echo $ _Post ["Color_1"]. "
";
Echo $ _post ["Color_2"]. "
";
Echo $ _Post ["Color_3"]. "
";
Echo $ _Post ["Color_4"]. "
";
Echo "About me:" $ _ post ["About"]. "


";
}
?>

The IF condition written is written: if there is a global variable $ _post ["submit"], then display data on the screen. This global variable is created if we click on the Send button, for which this example requires the NAME attribute in the button. You can quite wonder why the button attribute NAME is not required? Everything is quite simple. Usually the programmer does not track the press of the button, and tracks the sent data. For correct operation, for example, the contact form, you must track down without pressing the button, but the correctness of the input of information, and learn whether this information was introduced at all. In our example, we did not check the sent data, and simply traveled to press the button, to simplify the example ... That's what we did:

Conclusion

Well, for today we have disassembled two methods of data transfer between the scripts, and gallopam familiar with the forms. I really hope that this information you have at least somewhere useful. If you have any questions, or thoughts, write comments. Good luck to you, today I have everything!

P.S.: Do you want computer games have become even more realistic? DirectX 11 For Windows 7 You can download free on Windows in! Enjoy wonderful graphics!

This post is the answer to the question set in the comments to one of my articles.

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

Http.

So, what is one of the main Internet protocols? Pedants send to RFC2616, and the rest will tell about humanly :)

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

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

Method URI Http / Version. ,

Where Method is just the HTTP query method, the URI is the resource identifier, version is the version of the protocol (currently updated version 1.1).

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

The message body is, in fact, the data transmitted. In response transmitted data, as a rule, the HTML page that the browser requested, and in the query, for example, in the message body, the contents of files downloaded to the server are transmitted. But as a rule, the message body in the query is generally absent.

An example of http interaction

Consider an example.

Inquiry:
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 headlines; There is no body message

Answer:
HTTP / 1.0 200 OK Server: NGINX / 0.6.31 Content-Language: RU Content-Type: text / html; Charset \u003d UTF-8 Content-Length: 1234 Connection: Close ... HTML Page ...

Resources and methods

Let's go back to the starting line of the request and remember that it presents such a parameter as URI. This is decrypted as UNIFORM Resource Identifier - a uniform resource identifier. The resource is, as a rule, the file on the server (example of the URI in this case "/STYLES.CSS"), but at all, there may be any abstract object ("/ blogs / WebDev /" - indicates the block "Web Development ", not on a specific file).

The HTTP query type (also called the HTTP method) indicates the server to the fact that we want to produce with a resource. Initially (in the early 90s) it was assumed that the client could only want one to get it from the resource - to get it, but now, by the HTTP protocol, you can create posts, edit profile, delete messages and much more. And these actions are difficult to combine the term "receipt".

To delimit action with resources at the HTTP method level and the following options were invented:

  • Get - Getting a Resource
  • POST - resource creation
  • PUT - resource update
  • Delete - Delete Resource
Pay attention to the fact that the HTTP specification does not oblige the server to understand all methods (which is actually much more than 4) - only the GET is required, and also does not indicate the server that it should do when receiving a request with one or another method. And this means that the server in response to the delete /index.php request http / 1.1 is not obliged to Delete index.php page on the server, as well as to get /index.php HTTP / 1.1 request is not obliged to Return the index.php page to you, it can delete it, for example :)

REST enters the game

REST (REPRESENTATIONAL STATE TRANSFER) is the term was introduced in 2000 by ROEM Fielding (Roy Fielding) - one of the developers of the HTTP protocol - as the name of the group of the principles of web applications. In general, the REST covers a wider area than http - it can be applied in other networks with other protocols. REST describes the principles of client's interaction and server, based on the concepts of "resource" and "verb" (you can understand them as subject to both). In the case of HTTP, the resource is determined by its URI, and the verb is an HTTP method.

REST proposes to refuse to use the same URI for different resources (that is, the addresses of two different articles like /Index.php?article_id\u003d10 and /index.php?article_id\u003d20 is not the 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 accessing it with the HTTP method of Delete (of course, this does not mean that it is necessary to give the opportunity to remove everything and everything, but any A request for deletion in the application must use the HTTP-Delete method).

REST gives programmers the ability to write standardized and slightly more beautiful web applications than before. Using the REST, URI to add a new user will not be no /user.php?Action\u003dCreate (GET / POST method), and simply /User.php (Strict POST method).

As a result, together the existing Specification HTTP and the REST approach finally acquire the meaning of various HTTP methods. Get - Returns the resource, POST - creates a new, PUT - updates the existing, delete - deletes.

Problems?

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

PUT / DELETE Requests can be sent via XmlHttpRequest, by referring to the Manual 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 sending data differently than via GET or POST. Therefore, for normal operation with other methods, they have to imitate them artificially. For example, in Rack (a mechanism on the basis of which Ruby interacts with the web server; with Rack, RAILS, MERB and other Ruby frameworks are made) in the form you can add a hidden field called "_Method", and as a value specify the name of the method (For example, "PUT") - In this case, a post-request will be sent, but Rack will be able to pretend that I got PUT, and not POST.

This post is intended to explain the principles of data transfer on the Internet with the help of two main methods: Get and Post. I wrote it as a supplement to the instructions for the generator of a changeable schedule of work for those who are hardly interesting for the details ☺.

Go to the following address (this is for a visual explanation): http://calendarin.net/calendar.php?year\u003d2016 Please note the address bar of the browser: calendarin.net/calendar.php ? year \u003d 2016 The main file is called, followed by a question mark (?) And the "Year" parameter with the value "2016". So, everything that follows a question mark, this is a get-request. Everything is simple. To transmit not one parameter, but a few, then they need to divide the ampersand (&). Example: calendarin.net/calendar.php. ? year \u003d 2016 & Display \u003d Work-Days-and-Days-off

The main file is also called, followed by a question mark (?), Then the "Year" parameter with the value "2016", then ampersand (&), then - the "Display" parameter with the "Work-Days-and-Days" parameter -OFF.

Get-parameters can change directly in the browser address bar. For example, changing the value "2016" to "2017" and pressing the key, you will go to the calendar for 2017.

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

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

In addition to the GET method, which we reviewed in the previous note, there is another method of sending a query on the HTTP protocol - the POST method. The POST method is also very often used in practice.

If, in order to refer to the GET method, it is enough for us to type the request to the URL, then everything works in the POST method on another principle.

In order to execute this type of request, we need to click on the button with the Type \u003d "submit attribute", which is located on the web page. Please note that this button is located in the element. With the Method attribute with the POST value.

Consider this HTML code:

Enter the text:


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

POST and GET requests with simple words

This variable will be sent by the POST method.

If you write in the form:

That data will be sent by the GET method.

If, in the case of a get request, the amount of data that we could transmit is limited to the browser length length, then in the case of the post request, there is no such restriction, and we can transmit significant amounts of information.

Another difference of the POST method from GET, the POST method hides all the variables transmitted to them and their values \u200b\u200bin its body (Entity-Body). In the case of the GET method, they were stored in the query string (Request-URI).

Here is an example of a request made by 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 \u003d 1 \\ R \\ n
Content-Type: Application / X-WWW-FORM-URLENCODED \\ R \\ N
Content-Length: 35 \\ R \\ N
\\ r \\ n
Login \u003d Dima & Password \u003d 12345

Thus, passing data by the POST method, they will be much more difficult to intercept the attacker, because They are hidden from direct viewing, so the method of transmitting data by the POST method is considered to be more secure.

In addition, the POST method can be transmitted not only text, but also multimedia data (pictures, audio, video). There is a special content-type parameter that defines the type of information to be transmitted.

And finally, to get the data that were transmitted by this method, 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 requests to the HTTP server, and the server sends an HTTP response to the HTTP client. These requests and answers are issued according to certain rules. There is something like syntax, as in which sequence should be written. There must be a strictly defined structure.

Let us consider this structure in more detail, which builds requests and answers in the HTTP protocol.

HTTP request consists of three main parts that go in it in the order that is listed below. There is an empty line between the headers and body of the message (as a separator), it is a string translation symbol.

Empty string (separator)

POST and GET requests, what is the difference between them and what is better and for what purposes?

message Body (Entity Body) - optional parameter

Row request - Indicates the transfer method, the URL address to which the HTTP protocol version needs to be accessed.

Headlines - describe the message body, transmit different parameters and other information and information.

message body - This is the data that is transmitted in the request. The message body is an optional parameter and may not be missing.

When we get a response from the server, the message body is most often the contents of a web page. But, when queries to the server, it can also sometimes be present, for example, when we convey the data that was filled in the feedback form to the server.

In more detail, each query element, we will look at the following notes.

Let's, for example, consider one real request to the server. I highlighted each part of the query by my color: a query line - green, headlines - orange, the body message is blue.

Request from browser:

Host: Webgyry.info.

Cookie: WP-SETTINGS

Connection: Keep-Alive

The following example already has a message body.

Server Answer:

Content-Type: text / html; Charset \u003d UTF-8

Transfer-encoding: chunked

Connection: Keep-Alive

Keep-Alive: Timeout \u003d 5

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

Document Untitled

Here are the messages of the client and the HTTP server.

By the way, do you want to know whether it makes sense in some item on your site using the "goals" of Yandex Metrics and Google Analytics?

Remove what does not work, add what works and double your revenue.

Course on setting the goals of Yandex Metrics ..

Google Analytics Goals Setup Course ..

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

  • Query Row (Mandatory Element)
  • Title (optional element)
  • Empty string (mandatory element)
  • Message body (optional element)

Consider each of these elements separately.

Row request

The query string begins with a method token, after which the URI query and the protocol version follow. Elements are scattered from each other spaces:

Consider this item in more detail

Request method

This element indicates a method that must be called on the server side to the specified URI inferction.

There are eight methods in HTTP:

  • Head.
    Used to get the status string and header from the URI server. Does not change the data.
  • Get.
    Used to receive data from the server to the specified URI. Does not change the data.
  • POST.
    Used to send data to the server (for example, information about the developer, etc.) using HTML forms.
  • Put.
    Replaces all previous data on the resource new downloaded data.
  • Delete.
    Removes all current data on a resource defined by URI.
  • Connect.
    Sets the tunnel connection to the server according to the specified URI.
  • Options.
    Describes the connection properties for the specified resource.
  • Trace
    Provides a message containing the return trace of the resource specified in the URI.

URI request

URI (Uniform Resource Identifier) \u200b\u200bis a resource identifier to which the query is sent. Below is the most common URI format:

‘*’ Used when an HTTP request does not apply to a specific resource, but to the server. Used only in the case when the method is not necessary to apply to the resource. For example,

absoluteuri. Used when an HTTP request is performed on a proxy. Proxy is requested to transmit a query from an affordable cache and returns the answer. For example:

Asbutivated_Put | a sourcethe most Chatso is used.

Learning to work with Get and Post Requests

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

Request header fields

The header fields allow the client to transfer additional information about the request and about themselves to the server itself. These fields act as query modifiers.

Below is the intersection 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 decide to implement your own client and your own web server, then we can create your own header fields.

An example of http request

On this we finish learning HTTP requests.
In the next article, we will look at HTTP answers.

One way to send a request via HTTP to the server is to request the GET method. This method is the most common and requests to the server most often occur with its use.

The easiest way to create a Get query can be used to type the URL in the address bar of the browser.

The browser will send the server for approximately the following information:

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 \u003d 0.9, * / *; q \u003d 0.8
Accept-Language: RU-EN, RU; Q \u003d 0.8, EN-US; Q \u003d 0.5, EN; Q \u003d 0.3
Accept-Encoding: Gzip, Deflate
Cookie: WP-SETTINGS
Connection: Keep-Alive

The request consists of two parts:

1. Request Line (Request Line)

2. Headers (Message Headers)

Please note that the GET query does not have a message body. But, this does not mean that with it, we cannot transfer any information to the server.

Difference between GET and POST methods

This can be done with the help of special GET parameters.

To add GET parameters to request, you need to put a sign "?" At the end of the URL address And after it to start setting them at the following rule:

parameter_name1 \u003d Value Parameters1 & Parameter Name2 \u003d Value Parameters2 & ...

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

For example, if we want to pass two values, the username and its age, this can be done next line:

http://site.ru/page.php?name\u003ddima&age\u003d27

When this query is executed, the data fall into the so-called query_string environment variable from which they can be obtained on the server using the web programming server.

Here is an example, as can be done on PHP.

Echo "Your name:". $ _Get ["Name"]. "
»;
Echo "Your age:". $ _Get ["Age"]. "
»;
?>

The $ _GET design ["parameter name"] allows you to display the value of the transmitted parameter.

As a result of the execution of this code in the browser will be displayed:

Your name: Dima
Your age: 27

we also perform a request to the GET server.

In common between them, the fact that they work equally. The difference between them is technically no. But there is ideological differences.

I will tell about them in the context of PHP. Please note that the HTTP protocol to PHP has an indirect attitude because it was created to exchange HTML pages and PHP simply expands the possibilities and the other.

Get a query is used to get data A POST to send. (I remind you that technically work equally).

Therefore, in the context of PHP, relying on this ideology was made as follows:
1. Each time PHP is launched, superglobal arrays ($ _Get, $ _Post) are created by default.
2. If there is a question mark in the query string (?). Then everything is considered after it parameters GET requests they are presented in the "key" format \u003d "value" and an ampersand sign (&) is used as a separator
Example:
Get /index.php?name\u003dandrey&surname\u003dHalkin
This is a query string, here 2 parameters. These parameters will fall into the $ _get array.
3. $ _Post is filled with another way. The contents of this array are filled from the "request headers". That is, from the place hidden from the eyes explicitly. The whole routine to create such headlines takes on a browser. Although sometimes something is edited in headlines into manual.

Most often, the post request is used in forms (to send data).

For example, we have a form to log in 2 fields login and password.

Imagine that we use the GET method. Then, when sending a form, we turn to the following address /Login.php?Login\u003dandrey&password\u003d123 Agree that this is not safe to transmit such information. Anyone can open your browser and starting to enter the site address. It can see your passwords and login.

But if we specified by the POST method, then we would get the following request:
POST /LOGIN.php (login \u003d Andrey & Password \u003d 123) Whats in brackets would be hidden and not saved in the browser.

In general, summarizing:
Get is to get a certain page in a specific form (sorting, the current page in the blog, the search string, etc.).
POST - for mandrel data that does not affect the page display, in the way that these data only affect the result of the script execution (logins, passwords, credit card numbers, messages, etc.).

And one more good news can be combined, for example
POST /INDEX.php?page\u003dlogin (login \u003d Andrey & Password \u003d 123) I think I have already explained enough that it turns out and what parameters to which array will fall.