What is the difference between the get and post methods? Passing Variables in PHP


You may have noticed that on most sites you can see the following addresses:

Http://site/index.php?blog=2

Here, even without knowing php, you can guess that we are accessing a file index.php But few people know what comes after the question mark. It's quite simple: ?blog=2 This is a declaration of the global variable "$_GET["blog"]" with the value "2". Thus, I pass a variable into the script that is responsible for displaying information from the database. Let's write a small script in which you can clearly see everything:

if(isset($_GET["blog"])) (
echo $_GET["blog"];
}
?>

We use the if() condition operator and the following line is used as a condition:

Isset($_GET["blog"])

isset() allows you to find out whether the variable specified in brackets exists, that is, the condition that I described in the code sounds like this: If the variable $_GET["blog"] exists, then display the contents of this variable on the screen. Here's what happened:

I think it’s clear A global variable is created $_GET with the identifier that we declared in the address bar ( in this case with the identifier “blog”)

Now I want to clarify one point. Suppose we need to declare two variables, how to do this? The first variable is declared after the question mark "?" The second variable is declared after the “&” sign ( To be honest, I don’t know what this sign is), here is an example declaration of three variables:

Http://site/index.php?a=1&b=2&c=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 a global variable $_GET["b"] and a global variable $_GET["c"] then display them on the screen, here is the result:

Forms

Before we get to post requests, you need to understand what forms are? Why is it necessary? Because the global variable $_POST[""] is created through forms. What is form? These are fields for the user to enter some information. There are one-line fields, large fields, and also radio buttons and check boxes. Let's take everything in order...

The form is a tag:


form elements

The form has attributes, I will list the most common ones:

Let's create a form:


form elements

I set the file as a handler file test.php since it is in it that I write examples for you. I set the sending method to post because these are the methods used in 99.9% of cases. I also gave our form a name - form

Now let's plunge into the world of form elements. The first thing you need to understand is that almost all elements are a tag the only difference is in the attribute type at these tags. Let me list the form elements used:

I’m sure you’ve seen such fields more than once, so here’s what they say: “no comments”

Now let's create a small training questionnaire, which we will work with further. Our task is to create a small questionnaire that will tell us the name of the person filling it out, gender, what country they are from, favorite color and a text field where the user can add something about themselves. Here's what I got:

Your Last Name First Name Patronymic:

What's your gender:
M
AND

What country are you from



Favorite color(s):

Black:
Red:
White:
Another:

About Me:




Note that almost every tag has an attribute value, what is it for? It records the data that you are going to transfer to another page. I hope it's clear

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

For the form I used the attribute action with meaning test.php this means, as I already said, that the data from the form will be transferred to the test.php file.

POST request

Now let's write PHP code that will allow us to see the information we entered. Where is the data stored? In the case of the get request, our data was in the global variable $_GET[""]. When making a post request, the data will be stored in the global variable $_POST[""]. In square brackets, you must write, as in the case of the global variable get, an identifier. The question is, where can I get this identifier? That's why we need the name attribute on form elements! It is these names that serve as our key in the global post array. Well, let's start describing the script:

if(isset($_POST["submit"])) (
echo "Full name: ".$_POST["fio"]."
";
echo "Gender: ".$_POST["sex"]."
";
echo "Country of residence: ".$_POST["city"]."
";

Echo "Favorite color(s):
";
echo $_POST["color_1"]."
";
echo $_POST["color_2"]."
";
echo $_POST["color_3"]."
";
echo $_POST["color_4"]."
";
echo "About yourself: ".$_POST["about"]."


";
}
?>

The if condition we wrote says: If there is a global variable $_POST["submit"] then we display the data on the screen. This global variable is created if we click on the submit button, which is why the name attribute is needed in the button in this example. You may well be wondering why the button's name attribute is optional? It's quite simple. Typically, the programmer does not monitor the button press, but rather monitors the data sent. For correct operation of, for example, a contact form, it is necessary to track not the click of a button, but the correctness of the information entered, and to find out whether this information was entered at all. In our example, we did not check the sent data, but simply tracked the button press, to simplify the example... This is what we got:

Conclusion

Well, today we looked at two methods of transferring data between scripts, and we also got acquainted with forms. I really hope that this information will be useful to you at least somewhere. If you have any questions or thoughts, write comments. Good luck to you, that's all for today!

P.S.: Do you want computer games to become even more realistic? directx 11 for windows 7 can be downloaded for free on windows in! Enjoy wonderful graphics!

  • The POST method transfers data in such a way that the site user no longer sees the data sent to the script:
    http://www.komtet.ru/script.php

Both methods successfully transfer the necessary information from the web form to the script, so when choosing one or another method that will be most suitable for your site, you need to consider the following factors:

  1. The operating principle of the GET method limits the amount of information transferred to the script;
  2. Since the GET method sends all collected form information to the script as part of the URL (that is, in clear text), this can have a detrimental effect on the security of the site;
  3. A page generated by the GET method can be bookmarked (the page address will always be unique), but a page generated by the POST method cannot be bookmarked (the page address remains unchanged, since the data in the URL is not substituted);
  4. Using the GET method, you can transfer data not through a web form, but through the page URL by entering the necessary values ​​using the & sign:
    http://www.komtet.ru/script.php?login=admin&name=komtet
  5. The POST method, unlike the GET method, allows you to transfer files to the request;
  6. When using the GET method, there is a risk that the search robot may perform one or another “open request”

To show more clearly difference between POST and GET, I provide a table that shows by what characteristics they differ.

Based on this characteristic, we can conclude when to use POST, and when GET. For example, if the user wants to bookmark the generated page. Then generation should occur by GET request, otherwise you won’t be able to bookmark the page. Another example: when passing login and password, you cannot set the method GET, since it is based on transmitting data through the address bar. Otherwise, after pressing the “ Submit“, something like this will appear in the address bar: “ http://test.ru/login.php?log=User&pass=123“, - and anyone can see the password, which, of course, should not be allowed. Therefore, here we need to use the method POST.

Also, do not forget that the size of the data that can be passed by the method POST, an order of magnitude greater than when transmitted by the method GET. In general, analyze this table and draw a conclusion: which data transfer method should be used in a particular case. On my own behalf I will add that in 80% cases must be used POST, but don’t forget that this is far from 100% .

This post is intended to explain the principles of data transmission on the Internet using two main methods: GET and POST. I wrote it as a supplement to the instructions for the shift schedule generator for those who are unlikely to be 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 the value "2016". So, everything that follows the question mark is a GET request. It's simple. To pass more than one parameter, they need to 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 the value “2016”, then an ampersand (&), then a “display” parameter with the value “work-days-and-days” -off".

GET parameters can be changed directly in the browser 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 hidden transfer of data (the page address does not change); that is, you can only see what was transferred using a program (script). For example, in the following tool for counting characters in text, the original data is transmitted using the POST method: http://usefulonlinetools.com/free/character-counter.php

If you have any questions, comments and my email is at your service.

In addition to the GET method, which we discussed in the previous post, 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 contact the server using the GET method, we only had to type a request into the URL, then in the POST method everything works on a different principle.

In order to execute this type of request, we need to click on the button with the type="submit" attribute, which is located on the web page. Please 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, 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 words

This variable will be sent using the POST method.

If you write this in the form:

Then 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 limitation, 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 the variables it passes and their values ​​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, by 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 transmitting 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 parameter Content-Type that determines the type of information that needs to be transmitted.

And finally, in order to receive 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 post, 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 formatted according to certain rules. There is something like a 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 by which requests and responses are built 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 a line feed character.

Empty string (delimiter)

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 be accessed, and the HTTP protocol version.

Headings– describe the body of messages, transmit various parameters and other information and information.

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

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.

We will look at each element of the request in more detail in the following notes.

Let's, for example, consider one real request to the server. I've highlighted each part of the request with a different color: the request line is green, the headers are orange, and the message body 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

Untitled document

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

By the way, do you want to find out if there is any point in some element on your website using the “goals” of Yandex Metrics and Google Analytics?

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

Course on setting up Yandex Metrica goals..

Course on setting up Google Analytics goals..

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

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

Let's look at each of these elements separately.

Query string

The request line begins 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 a method that should be called on the server side at the specified URI.

There are eight methods in HTTP:

  • HEAD
    Used to get the status and header string 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 developer information, etc.) using HTML forms.
  • PUT
    Replaces all previous data on the resource with the new loaded data.
  • DELETE
    Deletes 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 return trace 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 commonly used URI format:

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

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

absolute_path | source most commonly used.

Learning to work with GET and POST requests

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

Querying header fields

Header fields allow the client to pass additional information about the request and 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
  • Referrer
  • User-Agent

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

Example HTTP request

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

One of the ways you can send an HTTP request to a server is with 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 address bar of your browser.

The browser will send the server 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=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 consists of two parts:

1. Request Line

2. Message Headers

Note that a GET request does not have a message body. But this does not mean that with its help we cannot transmit 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 add a “?” at the end of the URL. and after that start asking them according to the following rule:

parameter_name1=parameter_value1& parameter_name2=parameter_value2&…

The separator between parameters is the “&” sign.

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

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

When this request is executed, the data ends up in the so-called QUERY_STRING environment variable, from which it can be retrieved 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: " . $_GET["age"] . "
»;
?>

The $_GET[“parameter_name”] construction allows you to display the value of the passed parameter.

As a result of executing this code in the browser, the following will be displayed:

Your name: dima
Your age: 27

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

I think this article will not open America for many, and it seemed a little chaotic to me, so I had to smooth it out in places, but as an introduction to choosing between using a GET or POST request, I think this is it.

Unfortunately, in practice there are many inconsistencies in using GET instead of POST and vice versa. Both HTTP methods can produce the same results, but using them incorrectly can lead to unexpected and potentially dangerous consequences.

So to make sure we're doing it right, I'm presenting you with a guide to choosing between GET and POST.

Let's remember that in query strings, a variable/value pair is passed to GET via a URL request like this:

GET /blog/?name1=value1&name2=value2 HTTP/1.1 Host: carsonified.com

and in a POST request it is transmitted in the body of the header:

POST /blog/ HTTP/1.1 Host: carsonified.com name1=value1&name2=value2

Basics: GET vs POST

Let's introduce a new word into our vocabulary, the term is idempotent (You don't have to go to Wikipedia for its interpretation: idempotency is a property of an object that manifests itself in the fact that repeated action on this object does not change it), and sections 9.1, 9.3 and 9.5 of RFC 2616 will help us write the first GET vs. POST rule...

Rule #1: Use GET for secure actions and POST for unsecured ones

The RFC instructs Internet browsers to warn users about repeated using a POST request because this action is potentially unsafe (for example, making an online payment).

However, as long as the browser complies with this RFC requirement, can we clarify why POST should be used for unsecure activities, and why we should not use POST for secure ones?

Just take note that GET requests are used more often:

  1. GET requests can be cached
  2. GET requests may remain in the browser history
  3. GET requests can be saved in your bookmarks
  4. GET requests can be transmitted, distributed, etc.
  5. GET requests can be easily modified

Note: If you need to get the best of both worlds, you can make an unsafe action safe by making it idempotent and thus avoid the potential problem of multiple query repetitions. You assign each request its own unique ID and check it on the server to see if a request with that ID has been processed previously. In fact, all unsafe actions should be idempotent, since no warnings will stop the user.

GET vs POST: Digging Deeper

Rule #2: Use POST for transactions with sensitive information

Since GET requests have the query string in clear text, we must be concerned about our security and that users will be handling sensitive data such as passwords or credit card numbers:
1. Our users may be unaware of this when sharing sensitive data via URLs with others, or when their browser browsing history can be viewed by other users of that computer (although this may not work with AJAX-based services).
2. We ourselves violate the law on private information by storing, for example, CV2s numbers from users’ credit cards in our server logs.

Rule #3: Use POST for Big Data Operations

Although the RFC does not specify URL length, Internet Explorer is adamant that the maximum URL length cannot exceed 2,048 characters, which places some restrictions on the use of GET.

Rule #4: Use GET in AJAX Applications

When XMLHttpRequest is used, browsers implement POST as a two-pass process (sending the header first, then the data). This means that GET requests are more responsive, which is essential for a good AJAX environment.

Results

While rules are usually there for compelling reasons, it's good to know what's behind them. I myself hate rules that don't have explanations and I hope that the above will help you understand the rules of difference between GET and POST.

For a long time I wanted to write an article in which I would talk about difference between POST method and GET method, but somehow other topics appeared and I switched to them. And now, finally, the time has come to cover this topic, since often people simply do not know what is the difference between POST and GET.

To show more clearly difference between POST and GET, I provide a table that shows by what characteristics they differ.

Based on this characteristic, we can conclude when to use POST, and when GET. For example, if the user wants to bookmark the generated page. Then generation should occur by GET request, otherwise you won’t be able to bookmark the page. Another example: when passing login and password, you cannot set the method GET, since it is based on transmitting data through the address bar. Otherwise, after pressing the button " Submit", something like this will appear in the address bar: " http://mysite.ru/login.php?log=User&pass=123456", - and anyone can see the password, which, of course, should not be allowed. Therefore, here you need to use the method POST.

Also, do not forget that the size of the data that can be passed by the method POST, an order of magnitude greater than when transmitted by the method GET. In general, analyze this table and draw a conclusion: which data transfer method should be used in a particular case. On my own behalf I will add that in 80% cases must be used POST, but don’t forget that this is far from 100% .

If you have any questions or would like to comment on this article, you can leave your comment at the bottom of the page.

Comments (15):

dsmts 12.05.2013 14:00:18

Good afternoon I need something like this when redirecting: header("Location: test.php"); $_POST value was passed to this page. The page from which this value should be transmitted does not have any forms. Those. it simply processes the data and generates a specific request. At the moment I have the transfer done using cookies. But I'm not sure if it's safe. Or I'm wrong? The data that is transmitted should not be visible to users.

Answer

Alex_ 23.11.2013 23:56:10

Good day:), Mikhail! I'm trying to write a plugin in PHP and naturally discovered that I lack knowledge. Hence the question: if a certain site (payment system), after my actions on my side, sends me data to the site on a specific page using the POST method, should I see them if I write print_r($_POST) in the script? ? Just in my case, for example print_r($_SERVER); you can see what data is in the $_SERVER array, but $_POST is empty, that is, either the data does not arrive or I have a profane view of how things really are.

Answer

23.11.2013 23:59:31

Hello, Alexander Usually payment systems transmit data in reverse order in encrypted form and using secure protocols. So it all depends on the payment system. Are you writing a payment module for a specific system? Please clarify your queries otherwise I will not be able to help you.

Answer

Alex_ 24.11.2013 02:00:41

Hello Alexander, thanks for your response. I am writing a plugin for cms Wordpress, working with the interkassa.com payment system. If the purchase is successful, it redirects to the successful payment page http://my_site/success. According to the documentation, data that is visible to me comes to this page. That is, in the settings I selected the GET transfer method and a long url comes, this link and in it the parameters http://my_site/success/?&ik_payment_id=1&ik_paysystem_alias=yandexdengir, everything is as it should be. I tried to select the POST transmission method, then in the script I wrote, for example, if (isset($_POST["ik_trans_id"])) echo $_POST["ik_trans_id"]. And it worked. Then I started working with STATUS url because then ik_sign_hash arrives, which is generated by the intercash using a secret key (which is known to me and the intercash) and this time if (isset($_POST["ik_sign_hash"]) does not work because it is not there. On my site there is a plugin (it doesn’t do everything as we would like) written in OOP (I’m still far from the level of the one who wrote this, maybe that’s why it’s not obvious to me what is being used there). This plugin processes everything and calculates the hash on its side, because I deliberately changed the secret key (in the plugin settings) and an email was sent with a notification about incorrectly transferred data (the hashes did not match) and a request to contact the site administrator. Something like this.

Answer

24.11.2013 02:09:28

Well, I haven’t seen your plugin, so I won’t say anything specific. As for the simple implementation...I have not studied the interkassa API. You can see a simple solution here: http://goo.gl/rFnpNc Essentially, it’s the same in all systems. I usually work with a robotic cash register or onpei, so excuse me. In general, the structure is something like this. You need to write an implementation in accordance with the API documentation http://www.interkassa.com/faq.php see here the Interkassa section through the eyes of a programmer and administrator + There in the last question there is technical documentation for downloading and little things about the API in general

Answer

Alex_ 24.11.2013 02:16:40

Thank you, Alexander. I saw, I read all this, I’ve been trying for several days now and I google it and I think maybe I don’t understand something :). http://goo.gl/rFnpNc - and this is a plugin by Andrey Morkovin, not fully written (probably in order not to reveal all the secrets, the script is now paid). Several video lessons have been created based on it on how to write plugins on WP. This plugin http://www.icprojects.net/paid-downloads-plugin.html is available in paid and free versions. In the free version, only PAYPAL payment is available. but it’s all there and if you change a couple of values, the Interkassa mode in the beta version becomes available.

Answer

24.11.2013 02:23:00

Yes, I’m aware of this. There was just a plugin lying around. Whether it was complete or not, it worked. Maybe there’s a version somewhere that costs $40. lying around. In any case, I won’t recommend anything specific. Read the Interkassa API documentation. And the algorithms are the same everywhere. Write a handler that sends data in encrypted form and which receives and decrypts it in the same form. You can look at Levchuk’s solution in his wppage ;) If I have time, I’ll look at this topic in more detail







2024 gtavrl.ru.