Computers and modern gadgets

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, and 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 requests the response header and does not send the response body. For example, to check whether a page has changed, the browser may request the header, but this does not produce a full exchange of data.

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 making a GET request, the form data is sent to the server along with the URL. Web servers that support CGI copy this data to an environment variable called QUERY_STRING. After this, the CGI program is responsible for retrieving 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 password 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 places 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 a standard HTTP request that 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 be faced with the question: which of these methods to use. In most cases, both methods are applicable and both will work well. However, there are situations when using one or another method provides certain advantages.

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

  • If you want your program to be called using a 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 won't want the names and passwords stored in the report file. Additionally, it is not wise to pass the password as part of the URL.
  • If your form is large, such as text boxes with notes and comments, you should use the POST method. Generally speaking, you can use the GET method in this case, but then you may encounter URL size restrictions that vary for different operating systems and browsers (the limitation is due to 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. Additionally, in this case you need to set the ENCTYPE attribute value to multipart/form-data .

The use of GET and POST methods in PHP is difficult to overestimate, since these methods are found on almost every website. Before studying the material described below, I advise you to familiarize yourself with the html tag

. Let's look at each of these methods in detail.

GET method

The GET method uses a URL string to transfer data. You may have noticed long and unclear URLs. For example: function.php?login=Alex&email=dezyakin. In this case, the data is processed in function.php. After the question mark "?" there is a list of passed parameters (parameters are separated by "&") with values: the login parameter is assigned the value Alex, and the email variable is assigned the value dezyakin. The data will be stored in the superglobal array $_GET. An example of using the GET method is presented below:

Login : Email : Using the superglobal array $_GET, we display the accepted values:*/echo "
login = ". $_GET["login"] ; echo "
email = ". $_GET["email"] ; ?>

Notice how we read values ​​from the $_GET superglobal array: $_GET["variable_name"]. In our example, the variable names were declared in the form (name=login and name=email).

Advice:
Before processing the received values, I advise you to check for their existence through functions isset(variable_name) or empty(variable_name)- these functions were discussed in the previous lesson 2: variables in PHP. For example:

checking for existence using isset: if isset ($_GET["login"] ) ( operators for handling login ... } //or check for existence using empty: if empty ($_GET["email"] ) ( operators for email processing ... } ?>

In the form, you can specify the name of the file that will process the passed values. This is done using the action form attribute, which can be assigned the address of this file. By default, this file is assigned to the current file (that is, it is processed in the file where the form is located). Let's give an example in which the data from the form is transferred to the srcipt.php file for processing:

Login : Email :

The script.php file must contain some kind of information handler, otherwise the information will be passed to empty.

The GET method has many disadvantages:

  • The user sees the values ​​of the passed parameters;
  • The user can easily fake the passed parameters;
  • Inconvenient transfer of binary information (you have to encode in text format);
  • The amount of transmitted data is limited - 8 KB;

Due to the above disadvantages, the GET method is used only in cases where a small amount of data needs to be transferred, and this data is not classified in any way.

POST method

The POST method differs from the GET method in that the data is transmitted in a private form. There is a superglobal array $_POST , from which you can read data like this: $_POST["variable_name"]. For example:

Login : "> Email : ">
Using the $_POST superglobal array, we display the accepted values:*/echo "
login = ". $_POST["login"] ; echo "
email = ". $_POST["email"] ; ?>

The result of executing the above code is shown in the figure below:

As you can see, the URL does not have any attachment, but nevertheless the data was received and displayed.

Note:
1) The amount of values ​​transferred by the POST method is limited by default and equals 8 MB. To increase this value, you need to change the post_max_size directive in php.ini.

2) In early versions of PHP, instead of the short names of the superglobals $_GET and $_POST , longer names were used: $HTTP_GET_VARS and $HTTP_POST_VARS . By default they are disabled in PHP 5, but you can enable them in the php.ini configuration file using the register_long_arrays parameter. In php 6 version these long names will not be available.

3) Before processing variables from $_POST, I advise you to check the variables for their presence, just as was done with the GET method.

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 obtain 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 script being invoked to process the received information. To explain this method, type the URL of the resource in the browser's address bar and add first a question mark (?) and then the line num=10. For example

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


If you have a local server, then usually the domain will be localhost , and then the previous entry would look like

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


In this case, we pass a parameter num equal to 10. To add the following parameters, the script needs 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 the value 10, type with the value "new" and v with the value "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 the 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 parameters http://path/script.php, you will see errors that the interpreter will produce PHP, that there are no such elements of the $_GET array. More than one article could 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 is completely inconvenient. Therefore, to receive data from the user you need to use html forms. Let's write a simple html form.


Enter the number

Do you have a PC?

Your comment:





Let me comment a little on the created form. Forms are created with the form tag. Form fields are created using the 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 specified our existing script.php file. The method attribute specifies the method for sending data. We have specified the method GET. Now we know which file the form data will be transferred to, and in what way, all that remains is to figure out where to look for it?!
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, the value will be the text entered by the user. If the field is a list, a group of radio buttons or check boxes, 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 name attribute of the input tag) and the value will be 10 (the number entered by the user). Accordingly, the browser will generate a pair "num=10". If the user selects the "Yes" option from the list, then the name of the parameter 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 generate a “type=yes” pair.
Now we will place this form on the forma.php page.



Form for transmitting data using GET and PHP methods



Enter the number

Do you have a PC?

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 look at how the method works POST.
To send data using POST you need to use HTML forms. As we remember, the method attribute of the form tag is responsible for the method of sending form data. Therefore, you need to specify the value POST in the method attribute of the form tag. Otherwise, the form can be the same as for the GET method. Let's change our form, which we have already used to transmit data using the GET method, to transmit using the POST method.


Enter the number

Do you have a PC?

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 on the forma_post.php page.



Form for transmitting data using POST and PHP methods



Enter the number

Do you have a PC?

Your comment:







Now we need to write a script that will process our form data.
To receive data in a script using 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 the use of the $_POST array. Therefore, it will not be difficult for us to write a script_post.php file:



Validating 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. 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 by method POST cannot be passed through the address bar of the browser. This essential difference must be remembered.
IN PHP Regardless of how the data was sent - the POST method or the GET method - you can receive 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 data transferred will depend on the browser - on the maximum permissible 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 browser address bar). And therefore they are more secure, and, consequently, the program processing this data is more protected in terms of security. Also, the volume of transmitted data is practically unlimited.
When choosing a data transfer method, you need to take into account the above features and choose the most appropriate method.

HTML forms. $_POST and $_GET arrays

HTML forms. Methods for sending data to the server

You've probably already encountered HTML forms:

Enter your name:

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

Tag

, having 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 sent. If this attribute is not specified, most browsers (more precisely, all browsers known to me) send the form to the current document, that is, “to itself.” This is a convenient shorthand, but according to the HTML standard, the action attribute is required.
  • method - method of submitting the form. There are two of them.
    • GET - sending form data in the address bar.
      You may have noticed on various websites the presence of a "?" at the end of the URL. and the following data in the format parameter=value. Here the "parameter" corresponds to the value of the name attribute of the form elements (see below about the tag ), and “value” is the content of the value attribute (for example, it contains the user’s input into the text field of the same tag ).
      For example, try searching for something in Yandex and pay attention to the address bar of the browser. This is the GET method.
    • POST - form data is sent in the body of the request. If it’s not entirely clear (or completely unclear) what this is, don’t worry, we’ll return to this issue soon.
    If the method attribute is not specified, GET is assumed.

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

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

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

So what happens when we click "OK"?

  1. The browser looks at the elements included in the form and constructs 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 to the server a request for the document specified in the action attribute of the tag
    , using the data sending 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 (assuming the site's domain name is 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've probably already guessed, clicking the submit button on a form with a "GET" submit method is the same as typing the corresponding URL (with a question mark and form data at the end) into 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 be useful in practice.

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

We specified the sending method as "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 “two Enters” - in the body of the request. Everything above is actually the request header (and when we used the GET method, the form data was sent in the header). In order for the server to know at which byte to stop reading the request body, the header contains the line Content-Length; that the form data will be transmitted in the form parameter1=value1¶meter2=value2... , and the values ​​are transmitted in the form of urlencode - that is, exactly the same as using the GET method, but in the body of the request - 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 line.

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

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

$_GET and $_POST arrays

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

Consider a simple example:



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

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

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




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

- shortened form for .

Suppose we entered the value Vasya in the name field and clicked the OK button. In this case, the browser 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 reality, 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 automatically handles the necessary decoding, we can "forget" about this feature - until we have to deal with HTTP requests manually.

Since the body of the request specifies only names and values, but not form element types, PHP has no idea whether $_POST["name"] matches an input string, a button, or a list box. But we, in general, do not need this information at all. :)

Since we don't need to know what the submit button says, we can remove the name attribute on line 11, shortening the button description 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 "

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

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





On line 8 one could just as easily write

: 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 the same 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 check if ($_SERVER["REQUEST_METHOD"] == "GET") is meaningless. Therefore, we resort to the isset() construct, which returns true if the variable is defined (that is, 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 verification method using isset() is universal; it could also be used for a POST form. Moreover, it is preferable because it allows you to find out 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 techniques are used here. Figure it out, run the code, try modifying...

Let's change the last example so that the user does not have to fill out the fields again. To do this, 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 "Please specify the year of birth! Valid range of values: 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 be somewhat confusing. Everything is 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 point is that if these POST variables are not defined - and this will be the case if the form has not yet been filled out - PHP will issue warnings about the use of uninitialized variables (and, quite reasonably: such a message allows you to quickly find hard-to-detect 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 be too cumbersome.

Got it? Now try to find the error in the given code. Well, not exactly a mistake, but a flaw.

htmlspecialchars()

Didn't find it? I'll give you a hint. Enter, for example, in the “name” field a double quote and some text, for example, “Va” Send the form, and take a look at the source code of the resulting page. The fourth line will have something like:

Enter your name:

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

To solve this problem, you need to use the htmlspecialchars() function, which will replace the special 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 "Please specify the year of birth! Valid range of values: 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 displaying the contents of a variable that may contain HTML special characters.

phpinfo()

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

Why am I mentioning it in an article on forms? phpinfo() is a convenient debugging tool. phpinfo(), among other things, prints the values ​​of all $_GET, $_POST and $_SERVER variables. So if a form variable gets lost, the easiest way to find out what's wrong is to use the phpinfo() function. To ensure that the function displays only the values ​​of variables (and without you having to scroll through dozens of pages), it should be called as follows: phpinfo(INFO_VARIABLES); , or - which is absolutely the same thing - phpinfo(32) ;.



">
Enter your name:


phpinfo(32);
?>

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

Today I wanted to delve a little into primitive things and describe what can be found on the World Wide Web in large quantities and without much difficulty. We will talk 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 learn about it (while understanding little in the IT field) often cannot understand what is written in many, many articles devoted to this topic. I’ll try to explain with my fingers what POST and GET requests are and what they are used for.
So, let's begin 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. Whatever one may say, these two entities 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 disadvantages. Firstly, anyone who is next to the user at the computer can easily spy on all the data, so using this type of request to transfer passwords is highly undesirable. Secondly, there is a limit on the length of the string that can be transferred from the site address field, which means that it will not be possible to transfer much data. 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 during development, but that’s another story...
Now let's talk about POST requests. Smart 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, a striking example where a POST request is used is registration on the site. The site asks for your data, you fill in this data and when you click on the “Registration” button you send your answer. Moreover, this data will not be displayed externally in any way. It is also worth noting that a fairly large amount of information can be requested - and the POST request has no restrictions. Well, if you touch on the minus, then such a request cannot be generated quickly. You can’t do this without special skills. Although in reality everything is not so difficult, but again, that’s another story.
Let's summarize. POST and GET requests are needed for “communication” between the user and the site. They are essentially almost the opposite of each other. The use of certain types of queries depends on the specific situation and using only one type of query is extremely inconvenient.

If you notice an error, select a piece of text and press Ctrl+Enter
SHARE:
Computers and modern gadgets