Post and get requests are what else. Learning to work with GET and POST requests

There are two concepts that are common to almost all programs - this is the processing of input data and the output of results. On this page, we will focus on handling input from CGI programs. First, where does the input come from, and second, how is the input passed to the server. To write effective CGI programs, you must be clear about these things.

A bit about HTTP

The server accepts three types of requests: GET, POST and HEAD. The program request to the Web server looks like this:

GET /index.html HTTP/1.0

The first part, in this case GET , is the request method, the second, index.html , is the requested URL, the third, HTTP/1.0 , is the protocol used by the client.

The two main request methods are GET and POST. These are the same methods that are available to you when creating a form. The HEAD method is rarely used by the browser because it only asks for a response header and no response body is sent. For example, to check if the page has changed, the browser might request a header, but this does not generate a full data exchange.

GET Method

By default, the request method is GET. The POST method is only used when explicitly specified in the form request. It is very important for a CGI programmer to understand that when a GET request is made, the form data is passed to the server along with the URL. Web servers that support CGI copy this data to an environment variable called QUERY_STRING . After that, it's up to the CGI program to take care of getting the data from the environment variable and processing it.

The URL with the query string looks like this:

http://www.domen-name.com/login.pl?nick=maks&psw=parol

Sign? separates the query string from the actual resource URL; nick and psw are variables passed to the server, maks and parol are their values ​​respectively.

POST Method

The POST method is used when explicitly specified in the form's METHOD attribute. Unlike the GET method, POST puts data not in the URL, but in the body of the request. A POST request is similar to an HTTP response in many ways. The first line is the standard HTTP request, which specifies the POST method. It may contain the necessary additional headers, separated from the request body by an empty line.

The body of the request when using the POST method is passed to the program as standard input.

Choosing between GET and POST

It is clear that when developing forms, the CGI programmer will face the question: which of these methods to use. In most cases, both methods are applicable and both will work well. However, there are situations where the use of one method or another provides certain advantages.

Let's look at a few situations where it makes sense to prefer the GET or POST method.

  • If you want your program to be called by reference, the GET method should be preferred.
  • If you do not want the arguments passed to your program to be written to the server's report file, use the POST method. For example, if a form requires a username and password, you probably don't want the usernames and passwords to be stored in the report file. Also, it's not wise to pass the password as part of the URL.
  • If your form is large, such as having text boxes with notes and comments, you should use the POST method. Generally speaking, you can use the GET method in this case too, but then you may encounter URL size limits that are different for different operating systems and browsers (limited by the size of the environment variables). It's easier to use the POST method.
  • If your form contains a file field, use the POST method. Also, in this case, you need to set the value of the ENCTYPE attribute to multipart/form-data .

Browser clients can send information to a web server.

Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are concatenated with equal signs, and different pairs are separated by an ampersand.

Name1=value1&name2=value2&name3=value3

Spaces are removed and replaced with a + character, and any other non-alphanumeric characters are replaced hexadecimal values. After the information is encoded, it is sent to the server.

GET Method

The GET method sends encoded user information appended to the page request. Pages and coded information are separated from each other? question mark.

http://www.test.com/index.htm?name1=value1&name2=value2

  • The GET method creates a long string that appears in your server logs in the browser's "Location" field.
  • The GET method is limited to send up to 1024 characters only.
  • Never use the GET method if you have a password or other confidential information to send to the server.
  • GET cannot be used to send binary data such as an image or text documents, to the server.
  • Data sent by the GET method can be accessed using the QUERY_STRING environment variable.
  • PHP provides the $_GET associative array to access all information sent using the GET method.

if($_GET["name"] || $_GET["age"]) ( echo "Welcome ". $_GET["name"]; echo "You are ". $_GET["age"]. " years old ."; exit(); )

Name: Age:

POST Method

Method POST passes information through HTTP headers. Information is encoded as described in the method case GET, and placed in the header QUERY_STRING.

  • The POST method has no limits on the size of the data that needs to be sent.
  • The POST method can be used to send ASCII as well as binary data.
  • The data sent by the POST method goes through the HTTP header, so security depends on the HTTP protocol. By using Secure HTTP, you can ensure that your information is secure.
  • PHP provides the $_POST associative array to access all information sent using the POST method.

Try the following example by placing the source code in the test.php script.

if($_POST["name"] || $_POST["age"]) ( if (preg_match("[^A-Za-z"-]",$_POST["name"])) ( die (" invalid name and name should be alpha"); ) echo "Welcome ". $_POST["name"]; echo "You are ". $_POST["age"]. " years old."; exit(); )

Name: Age:

Variable $_REQUEST

PHP Variable $_REQUEST contains content like $_GET, $ _POST and $_COOKIE. We will discuss the variable $_COOKIE when we talk about cookies.

The $_REQUEST PHP variable can be used to get the result from form data submitted using the GET and POST methods.

What they have in common is that they work in the same way. There is no technical difference between them. But there are ideological differences.

I will talk about them in the context of PHP. Please note that the HTTP protocol to PHP is indirectly related because it was created for the exchange html pages and PHP just extends the possibilities of both.

GET request is used to get data and POST is used to send. (I remind you that technically they work the same way).

Therefore, in the context of PHP, based on this ideology, they did the following:
1. Every time you start PHP, superglobal arrays ($_GET, $_POST) are created by default.
2. If there is a question mark(?) in the query string. Everything after it counts parameters GET request, they are represented in the format "key"="value" and the ampersand sign (&) is used as a separator
Example:
GET /index.php?name=Andrey&surname=Galkin
this is a query string, there are 2 parameters. these parameters will end up in the $_GET array.
3. $_POST is filled in a different way. the content of this array is populated from "request headers". That is, from a place hidden from the eyes in an explicit form. The browser takes care of the whole routine of creating such headers. Although sometimes something is edited in the headings manually.

Most often, a post request is used in forms (for sending data).

For example, we have a login form with 2 fields login and password.

Imagine that we are using the GET method. Then, when submitting the form, we will go to the following address /login.php?login=Andrey&password=123 agree that it is not at all safe to transmit such information in this way. Anyone can open your browser and starting to enter the site address, he can see your passwords and logins from the history.

But if we specified the POST method, then we would receive the following request:
POST /login.php (login=Andrey&password=123) what is in brackets would be hidden and not saved in the browser in any way.

To summarize in general:
GET is to get a certain page in a certain way (sorting, current page blog, search bar, etc.).
POST - for sending data that does not affect the display of the page, in the sense that this data only affects the result of the script execution (logins, passwords, credit card numbers, messages, etc.).

And one more good news, they can be combined, for example
POST /index.php?page=login (login=Andrey&password=123) I think I have already explained enough what will come of this and what parameters will go into which array.

Modern web resources not only provide information to the visitor, but also interact with him. To interact with the user, you need to receive some information from him. There are several methods to get data, very common methods are GET and POST. And accordingly in PHP there is support for these data transfer methods GET and POST. Let's see how these methods work.
GET method Data GET method are passed by adding them to the URL of the called script to process the received information. For clarification this method Type in the address bar of your browser the URL of the resource and add first a question mark (? ) and then the line num=10 . for instance

http://domain.ru/script.php?num=10


If you have local server, then usually the domain will be localhost , in which case the previous entry will look like

http://localhost/script.php?num=10


In this case, we are passing the num parameter equal to 10. To add the following parameters to the script, you need to use the ampersand (& ) separator, for example

http://domain.ru/script.php?num=10&type=new&v=text


In this case, we passed three parameters to the script: num with a value of 10, type with a value of "new" and v with a value of "text".
To get these parameters in the script, you need to use the built-in array $_GET $_GET["num"], $_GET["type"],$_GET["v"]. These array elements will contain the values ​​of the passed parameters. To demonstrate this example, create a script.php file with the following content



Validating the GET method in PHP


echo ($_GET["num"]."
");
echo ($_GET["type"]."
");
echo ($_GET["v"]);
?>


And now call this file in browser

http://path/script.php?num=10&type=new&v=text


and you will see the passed parameters in the browser window. But if you call this file without additional options http://path/script.php , you will see the errors that the interpreter will give PHP, that there are no such elements in the $_GET array. More than one article can be devoted to checking the data received from the user, so in this article I will not touch on this point.
As you probably understand, forcing the user to type data in the address bar of the browser is not very good and not at all inconvenient. Therefore, to receive data from the user, you need to use html forms. Let's write a simple html form.


Insert the number

Do you have a computer?

Your comment:





I will comment on the created form a little. Forms are created with the form tag. Form fields are created by input , select , textarea tags (you can read more). In the form tag, the action attribute specifies the URL of the script that will receive the form data. In our case, we have specified the script.php file that we already have. The method attribute specifies the method for sending data. We have specified a method GET. Now we know to which file the form data will be transferred, and in what way, it remains to figure out where to look for them there ?!
This form data will be passed to the web resource by the browser by appending it to the URL: first there will be a question mark (? ), then the parameters will be presented separated by an ampersand (& ). The name of the parameter will be taken from the name attribute, which must be specified for any form field. The value of the parameter will depend on the field type. If the field is a text field, then the value will be the text entered by the user. If the field is a list, a group of radio buttons or checkboxes, then the value of the parameter will be the value of the value attribute of the selected element. Let me explain with an example of our form. If the user enters the number 10 in the input field, then the name of the parameter will be num (the value of the input tag's name attribute), and the value will be 10 (the number entered by the user). Accordingly, the browser will generate a pair of "num=10 ". If the user selects "Yes" from the list, then the name of the option will be type (the value of the name attribute of the select tag), and the value will be yes (the value of the value attribute of the option tag). Accordingly, the browser will form a pair of "type=yes ".
Now we will place this form on the page forma.php .



Form for data transfer by GET method and PHP



Insert the number

Do you have a computer?

Your comment:







Enter any values ​​in the form fields and click the "Submit" button. After clicking the button, the browser will open another page (script.php ) and the data you entered will be displayed in the browser window. I think it's clear why: the browser will pass the data to the script.php script, and in the script this data will be processed and displayed on the screen.
POST Method Now let's see how the method works POST.
To send data by method POST You need to use HTML forms. As we remember, the method attribute of the form tag is responsible for the method of submitting form data. Therefore, you need to specify the POST value in the method attribute of the form tag. The rest of the form can be the same as for the GET method. Let's change our form, which we already used to send data using the GET method, to send it using the POST method.


Insert the number

Do you have a computer?

Your comment:





As you can see, the form remains the same except for the method and action attributes. The data will now be passed to the script_post.php script. Let's place our form in the forma_post.php page.



Form for data transfer by POST method and PHP



Insert the number

Do you have a computer?

Your comment:







Now we need to write a script that will process our form data.
To receive data in the script by the passed method POST need to use built-in array $ _POST. The keys of this array will be the names of the parameters. In our case, we need to use $_POST["num"], $_POST["type"],$_POST["v"]. These array elements will contain the values ​​of the transferred data. As you can see, the difference from using the GET method is expressed only in using the $_POST array. Therefore, it will not be difficult for us to write a script_post.php file:



Checking the POST method in PHP


echo ($_POST["num"]."
");
echo ($_POST["type"]."
");
echo ($_POST["v"]);
?>


Now open the forma_post.php file in a browser. Enter some data in the form fields and click the "Submit" button. By now, you probably noticed the difference between the POST method and the GET method - the form data did not appear in the address bar of the browser. Data method POST cannot be passed through the address bar of the browser. This essential difference must be remembered.
V PHP regardless of how the data was sent - using the POST method or the GET method - you can get the data using the $_REQUEST array. Comparison of GET and POST Methods When using the GET method, data is transferred by appending to the URL. Thus, they will be visible to the user, which is not always good from a security point of view. Also, the maximum amount of transmitted data will depend on the browser - on the maximum allowed number of characters in the browser's address bar.
When using the POST method, the data will not be visible to the user (not displayed in the address bar of the browser). And therefore they are more secure, and, consequently, the program that processes this data is more secure in terms of security. Also, the amount of data transferred is practically unlimited.
When choosing a data transfer method, you need to take into account the above features and stop at the most appropriate method.

HTML forms. $_POST and $_GET arrays

HTML forms. Methods for sending data to the server

You have probably already met with HTML forms:

Enter your name:

By saving this code in an HTML file and viewing it with your favorite browser, you will see a familiar HTML form:

Tag

, which has a paired end tag
, actually sets the form. Its attributes are both optional:

  • action - Specifies the URL (full or relative) to which the form will be submitted. If this attribute is not specified, most browsers (more precisely, all browsers I know) submit the form to the current document, that is, "to itself". It's a convenient shorthand, but the HTML standard requires the action attribute.
  • method - how the form is submitted. There are two of them.
    • GET - send form data in the address bar.
      You may have noticed on various sites the presence of the "?" symbol at the end of the URL. followed by data in the format parameter=value. Here "parameter" corresponds to the value of the name attribute of the form elements (see below about the tag ), and "value" - to the content of the value attribute (for example, it contains the user's input in the text field of the same tag ).
      For example, try searching for something in Yandex and pay attention to the address bar of your browser. This is the GET method.
    • POST - form data is sent in the body of the request. If it is not entirely clear (or completely incomprehensible) what it is - do not worry, we will return to this issue soon.
    If the method attribute is not specified, GET is assumed.

Tag - specifies the form element defined by the type attribute:

  • The "text" value specifies a single-line text input field
  • The "submit" value specifies the button that, when clicked, submits the form to the server

Other values ​​are possible (and is not the only tag that defines a form element).

So what happens when we click the "OK" button?

  1. The browser looks at the elements included in the form and generates form data from their name and value attributes. Let's say the name Vasya is entered. In this case, the form data is name=Vasya&okbutton=OK
  2. The browser establishes a connection with the server, sends a request to the server for the document specified in the action attribute of the tag
    , using the data submission method specified in the method attribute (in this case, GET), passing the form data in the request.
  3. The server analyzes the received request, generates a response, sends it to the browser and closes the connection
  4. The browser displays the document received from the server

Sending the same request manually (using telnet) looks like this (assume that Domain name site - www.example.com):

Telnet www.example.com 80 GET /cgi-bin/form_handler.cgi?name=Vasya&okbutton=OK HTTP/1.0\r\n Host: www.example.com\r\n \r\n

As you might have guessed by now, clicking a submit button on a form with a "GET" submit method is the same as entering the appropriate URL (with a question mark and form data at the end) in the browser's address bar:

http://www.example.com/cgi-bin/form_handler.cgi?name=Vasya&okbutton=OK

In fact, the GET method is used whenever you request a document from the server by simply entering its URL or clicking on a link. Using , the URL is simply appended with a question mark and form data.

Perhaps all these technical details and exercises with telnet seem incredibly boring and even unnecessary to you ("what does PHP have to do with it?"). But in vain. :) These are the basics of working with the HTTP protocol, which every Web programmer needs to know by heart, and this is not theoretical knowledge - all this will come in handy in practice.

Now let's replace the first line of our form with the following:

We have specified the send method "POST". In this case, the data is sent to the server in a slightly different way:

Telnet www.example.com 80 POST /cgi-bin/form_handler.cgi HTTP/1.0\r\n Host: www.example.com\r\n Content-Type: application/x-www-form-urlencoded\r\ n Content-Length: 41263\r\n \r\n name=Vasya&okbutton=OK

When using the POST method, the form data is sent after the "two Enters" - in the request body. Anything above is actually the header of the request (and when we used the GET method, the form data was sent in the header). In order for the server to know on which byte to end reading the request body, the Content-Length line is present in the header; about the fact that the form data will be passed in the form parameter1=value1¶meter2=value2... , and the values ​​are transmitted in the form of urlencode - that is, in the same way as with the GET method, but in the request body - the Content header informs the server -Type: application/x-www-form-urlencoded .

The advantage of the POST method is that there is no limit on the length of the form data string.

With the POST method, it is not possible to submit the form by simply "following the link", as was the case with GET .

When using a POST form, in its action attribute, you can specify the GET form parameters after the question mark. Thus, the POST method includes the GET method as well.

Arrays $_GET and $_POST

So, forms are the main way to exchange data between a web server and a browser, that is, they provide interaction with the user - in fact, what web programming is for.

Consider a simple example:



if ($_SERVER [ "REQUEST_METHOD" ] == "POST" ) (
echo "

Hey, " . $_POST [ "name" ] . "

!" ;
}
?>
">
Enter your name:




The form shown in lines 8-12 contains two elements: name and okbutton . The method attribute specifies the POST form submission method, while the action attribute, which indicates the URL to which the form is submitted, is filled in with the value of the PHP_SELF server variable, the address of the currently executing script.

- abbreviated form for .

Suppose we entered the value Vasya in the name field, and clicked the OK button. The browser then sends a POST request to the server. Request body: name=Vasya&okbutton=OK . PHP automatically populates the $_POST array:

$_POST [ "name" ] = "Vasya"
$_POST [ "okbutton" ] = "OK"

In fact, the value "Vasya" is sent by the browser in urlencode form; for windows-1251 encoding this value looks like %C2%E0%F1%FF . But since PHP does the necessary decoding automatically, we can "forget" about this feature - until we have to work with HTTP requests manually.

Since the request body specifies only names and values, not form element types, PHP has no idea if $_POST["name"] matches an input string, a button, or a list. But we don't really need this information. :)

Since we don't need to know what is written on the submit button, on line 11 we can remove the name attribute, shortening the description of the button to . In this case, the browser will send a POST request name=Vasya.

And now - the same thing, but for the GET form:



if (isset($_GET [ "name" ])) (
echo "

Hey, " . $_GET [ "name" ] . "

!" ;
}
?>
">
Enter your name:





On line 8 one could just as well have written

: GET is the default method. This time, the browser sends a GET request, which is equivalent to entering the address in the address bar: http://site-address/script-name.php?name=Vasya.

PHP does exactly the same thing with GET forms as it does with POST , with the difference that the $_GET array is populated.

The cardinal difference is in line 4. Since simply entering the address in the browser line is a GET request, the if ($_SERVER["REQUEST_METHOD"] == "GET") check is meaningless. Therefore, we resort to the isset() construct, which returns true if the given variable is defined (i.e., it has been assigned a value), and false if the variable is not defined. If the form has been filled out - as you already understood, PHP automatically assigns $_GET["name"] the appropriate value.

The isset() check method is universal, it could also be used for a POST form. Moreover, it is preferable, as it allows you to find out exactly which form fields are filled out.

A slightly more complex example.




echo "Please enter a name!
" ;
< 1900 || $_POST [ "year" ] > 2004 ) {
echo
"
;
) else (

" ;

echo "You" . $age. " years
" ;
}
echo "


" ;
}
?>
">
Enter your name:


Enter your year of birth:





No new tricks are used here. Figure it out, run the code, try modifying...

Let's change the last example so that the user doesn't have to refill the fields. To do this, let's fill the value attributes of the form elements with the values ​​we just entered.



$name = isset($_POST [ "name" ]) ? $_POST [ "name" ] : "" ;
$year = isset($_POST [ "year" ]) ? $_POST [ "year" ] : "" ;

If (isset($_POST [ "name" ], $_POST [ "year" ])) (
if ($_POST [ "name" ] == "" ) (
echo "Please enter a name!
" ;
) else if ($_POST [ "year" ]< 1900 || $_POST [ "year" ] > 2004 ) {
echo "Enter year of birth! Valid range: 1900..2004
"
;
) else (
echo "Hello, " . $_POST [ "name" ] . "!
" ;
$age = 2004 - $_POST["year"];
echo "You" . $age. " years
" ;
}
echo "


" ;
}
?>
">
Enter your name:


Enter your year of birth:





Lines 4 and 5 may turn out to be somewhat incomprehensible. It's very simple: line 4 could be written like this:

if (isset($_POST [ "name" ]))
$name = $_POST["name"];
else
$name = "" ;

The question may arise - why not throw out lines 4-5 and write:

Enter your name: ">

Enter your year of birth: ">

The fact is that if these POST variables are not defined - and they will be if the form has not yet been filled out - PHP will issue warnings about the use of uninitialized variables (and, quite rightly: such a message allows you to quickly find hard-to-find typos in variable names, and also warns about possible "holes" on the site). You can, of course, put the isset code directly into the form, but it will turn out to be too cumbersome.

Got it? Now try to find the error in the above code. Well, not quite a mistake - but a flaw.

htmlspecialchars()

Didn't find it? I'll prompt. Enter, for example, a double quote in the "name" field and some text, for example, Vasya. Submit the form, and take a look at the source code of the received page. The fourth line will be something like:

Enter your name:

That is, nothing good. What if a cunning user entered a JavaScript code?

To solve this problem, you need to use the htmlspecialchars() function, which will replace service characters with their HTML representation (for example, a quote with "):



$name = isset($_POST [ "name" ]) ? htmlspecialchars ($_POST [ "name" ]) : "" ;
$year = isset($_POST [ "year" ]) ? htmlspecialchars ($_POST [ "year" ]) : "" ;

If (isset($_POST [ "name" ], $_POST [ "year" ])) (
if ($_POST [ "name" ] == "" ) (
echo "Please enter a name!
" ;
) else if ($_POST [ "year" ]< 1900 || $_POST [ "year" ] > 2004 ) {
echo "Enter year of birth! Valid range: 1900..2004
"
;
) else (
echo "Hello, " . $name . "!
" ;
$age = 2004 - $_POST["year"];
echo "You" . $age. " years
" ;
}
echo "


" ;
}
?>
">
Enter your name:


Enter your year of birth:





Repeat the experiment and make sure that the HTML code is now correct.

Remember - the htmlspecialchars() function must be used whenever the contents of a variable that may contain HTML special characters is displayed.

phpinfo()

The phpinfo() function is one of the most important functions in PHP. It displays information about PHP settings, the values ​​of various configuration variables...

Why do I mention it in an article on forms? phpinfo() is the most convenient debugging tool. phpinfo() outputs, among other things, the values ​​of all $_GET , $_POST , and $_SERVER variables. So if a form variable is "lost", the easiest way to find out what's wrong is to use the phpinfo() function. In order for the function to display only the values ​​of the variables (and you do not have to scroll through a dozen pages), it should be called as follows: phpinfo(INFO_VARIABLES); , or - which is exactly the same - phpinfo(32) ;.



">
Enter your name:


phpinfo(32);
?>

Or, for example, this situation: you want to know the visitor's IP address. You remember that the corresponding variable is stored in the $_SERVER array, but - bad luck - you forgot what exactly the variable is called. Again, we call phpinfo(32); , look for your IP address in the table and find it - in the line $_SERVER["REMOTE_ADDR"] .