Processing http requests php. Processing requests using PHP. Defining HTTP request parameters via HTML form




Browser clients can send information to the web server.

Before the browser sends 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 with hexadecimal values. Once the information is encoded, it is sent to the server.

GET method

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

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

  • The GET method produces a long string that appears in your server logs in the browser's "Location" field.
  • The GET method is limited to sending up to 1024 characters only.
  • Never use the GET method if you have a password or other sensitive information to send to the server.
  • GET cannot be used to transfer binary data, such as images 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 sent information 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 transmits information via HTTP headers. The information is encoded as described in the case of the method GET, and is placed in the header QUERY_STRING.

  • The POST method has no limit 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.
  • Data sent using the POST method passes through an HTTP header, so security depends on the HTTP protocol. By using Secure HTTP, you can ensure that your information is protected.
  • PHP provides an associative array $_POST 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:

$_REQUEST variable

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

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

For POST method

The form content is encoded in exactly the same way as for the GET method (see above), but instead of adding a string to the URL, the request content is sent as a data block as part of the POST operation. If the ACTION attribute is present, then the URL value found there determines where to send this block of data. This method, as already noted, is recommended for transferring large data blocks.

Information entered by the user and sent to the server using the POST method is served on standard input to the program specified by the action attribute, or to the current script if this attribute is omitted. The length of the sent file is passed in the environment variable CONTENT_LENGTH, and the data type is passed in the CONTENT_TYPE variable.

You can only send data using the POST method using an HTML form, since the data is sent in the body of the request, and not in the header, as in GET. Accordingly, you can change the value of the parameters only by changing the value entered in the form. When using POST, the user does not see the data sent to the server.

The main advantage of POST requests is their greater security and functionality compared to GET requests. Therefore, the POST method is more often used to transmit important information, as well as large-scale information. However, you should not rely entirely on the security of this mechanism, since the POST request data can also be faked, for example, by creating an HTML file on your machine and filling it with the necessary data. Additionally, not all clients can use the POST method, which limits its use cases.

When sending data to the server by any method, not only the data entered by the user is transmitted, but also a number of variables, called environment variables, characterizing the client, its operation history, file paths, etc. Here are some of the environment variables:

  • REMOTE_ADDR – IP address of the host (computer) sending the request;
  • REMOTE_HOST – host name from which the request was sent;
  • HTTP_REFERER – address of the page linking to the current script;
  • REQUEST_METHOD – the method that was used when sending the request;
  • QUERY_STRING – information located in the URL after the question mark;
  • SCRIPT_NAME – virtual path to the program that should be executed;
  • HTTP_USER_AGENT – information about the browser that the client uses

So far, we have only mentioned that client requests are processed on the server using a special program. In fact, we can write this program ourselves, including in PHP, and it will do whatever we want with the received data. In order to write this program, you need to become familiar with some of the rules and tools that PHP offers for this purpose.



Within a PHP script, there are several ways to access data sent by a client via HTTP. Before PHP 4.1.0, access to such data was carried out by the names of the transferred variables (remember that data is transferred in the form of pairs “variable name, “=” symbol, variable value”). Thus, if, for example, first_name=Nina was passed, then the $first_name variable with the value Nina appeared inside the script. If it was necessary to distinguish by what method the data was transferred, then the associative arrays $HTTP_POST_VARS and $HTTP_GET_VARS were used, the keys of which were the names of the transferred variables, and the values ​​were, respectively, the values ​​of these variables. Thus, if the pair first_name=Nina is passed by the GET method, then $HTTP_GET_VARS["first_name"]="Nina".

It is not safe to use the names of passed variables directly in a program. Therefore, it was decided, starting with PHP 4.1.0, to use a special array – $_REQUEST – to access variables transmitted via HTTP requests. This array contains data transferred using the POST and GET methods, as well as using HTTP cookies. This is a superglobal associative array, i.e. its values ​​can be obtained anywhere in the program using the name of the corresponding variable (form element) as a key.

Example 4.2. Let's say we created a form to register participants for a programming correspondence school, as in the example above. Then in the 1.php file that processes this form, you can write the following:

";$str .="You have chosen to study a course on ".$_REQUEST["kurs"];echo $str;?>

Then, if we entered the name “Vasya”, the surname “Petrov” into the form and selected the PHP course among all courses, we will receive the following message on the browser screen:

After the introduction of the $_REQUEST array, the $HTTP_POST_VARS and $HTTP_GET_VARS arrays were renamed $_POST and $_GET, respectively, for consistency, but they themselves did not disappear from use for reasons of compatibility with previous versions of PHP. Unlike their predecessors, the $_POST and $_GET arrays have become super-global, i.e. accessible directly and inside functions and methods.

Let's give an example of using these arrays. Let's say we need to process a form containing input elements named first_name, last_name, kurs (for example, the form.html above). The data was transferred using the POST method, and we do not want to process data transferred by other methods. This can be done as follows:

";$str .= "You have chosen to study a course on ". $_POST["kurs"];echo $str;?>

Then on the browser screen, if we entered the name “Vasya”, the last name “Petrov” and selected the PHP course among all courses, we will see a message, as in the previous example:

Hello, Vasya Petrov! You have chosen to study a PHP course

In order to maintain the ability to process scripts earlier than PHP 4.1.0, the register_globals directive was introduced, allowing or denying access to variables directly by their names. If the register_globals=On parameter is in the PHP settings file, then variables passed to the server using the GET and POST methods can be accessed simply by their names (i.e. you can write $first_name). If register_globals=Off, then you need to write $_REQUEST["first_name"] or $_POST["first_name"], $_GET["first_name"], $HTTP_POST_VARS["first_name"], $HTTP_GET_VARS["first_name"]. From a security point of view, it is better to disable this directive (i.e. register_globals=Off). With the register_globals directive enabled, the arrays listed above will also contain the data passed by the client.

Sometimes you need to know the value of an environment variable, such as the method used to send the request or the IP address of the computer that sent the request. You can get this information using the getenv() function. It returns the value of the environment variable whose name is passed to it as a parameter.

As we have already said, if the GET method is used, then the data is transferred by adding a query string in the form of variable_name=value pairs to the resource URL. Anything after the question mark in the URL can be retrieved using the command

Getenv("QUERY_STRING");

Thanks to this, it is possible to transfer data in some other form using the GET method. For example, you can specify only the values ​​of several parameters using a plus sign, and in the script you can parse the query string into parts, or you can pass the value of just one parameter. In this case, an empty element with a key equal to this value (the entire query string) will appear in the $_GET array, and the “+” character encountered in the query string will be replaced with an underscore “_”.

With the POST method, data is transmitted only using forms, and the user (client) does not see what data is sent to the server. To see them, the hacker must replace our form with his own. Then the server will send the results of processing the incorrect form to the wrong place. To avoid this, you can check the address of the page from which the data was sent. This can be done again using the getenv() function:

Getenv("HTTP_REFERER");

Now is the time to solve the problem formulated at the beginning of the lecture.

(Denver distribution) and you have learned how to write simple programs in PHP, then it’s time to learn how the browser (client) can make requests to the server and receive appropriate responses. Using the example of creating a simple HTML form, we will study the basic principles of such interaction.

If you are already well versed in the Denver directories, you can create any PHP file in a directory convenient for you and start writing code. For those who are not yet confident in their abilities, I advise you to do the following: on the virtual disk with Denver (usually Z) in the home folder, create a lessons folder. Next, in this folder, create another folder - www. This is your working project folder, which will be accessible from your browser's address bar. Reboot Denver so that the created host is registered in the system. Finally, in the www folder, create an index.php file. This will be the main file with your code.

As you can see, this is regular HTML markup, but we named the file index.php, which means that now we can insert any instructions in PHP into the document.

If you now go to http://lessons/ in your browser, you will see the following result:

Fill in the fields (for example: name – Vasya, year of birth – 1990) and click on the “send” button. What do you see? Nothing! Again the same form, only empty. However, do not rush to get upset - take a look at the address bar of your browser. It has changed and now looks something like this:

Http://lessons/index.php?user_name=Vasya&user_year=1990&submit_form=send

This means that the server finally received your data!

Let's figure it out now.

GET method

Firstly, what is an HTML form anyway? This is an interface that allows you to send any data from the client browser to the server. Take a look at your form's attributes:

The action attribute is responsible for the address of the recipient of the sent data. In our case, the form is sent to the same address, i.e. at lessons/index.php.

Particularly noteworthy is the method attribute, which defines the method for sending a request to the server. There are several such methods, and the most common (and practical) are the GET and POST methods. Now we will be interested in the GET method.

A GET request means that data will be sent to the server directly through the address bar. You have already seen this by submitting the form - certain data has been added to the address line. Where does this data come from? Pay attention to the input tags in the HTML form. They all have a name attribute, which sets the name of the field.

With the GET method, the character "?" is added to the main address. (question mark) so that the server understands that some data has arrived. After the "?" The data itself goes directly in the form name=value. If there is more than one such data, they are separated by the concatenation symbol "&". Submit the form with different field values ​​and see for yourself.

The time has come to learn how to “catch” and process the received data. Due to the fact that the action attribute points to the current index.php file, this means that the data comes here, so in the same file we will write the code for processing the GET request.

So, immediately after the tag Let's add this PHP code:

Save the file, go to http://lessons/ again, submit the form and - lo and behold! – what do you see?

Just after submitting the form, the server received and processed received data and sent your response to the browser!

Let's look at the PHP code of our project, which represents a condition:

If (isset($_GET["submit_form"])) ( )

The server checks whether a GET request variable named submit_form has been received? That is, to put it simply, was the form even submitted? If so, the server-side PHP code sends new HTML markup with its response directly to the user's browser using the echo statement. If you carefully study the written handler code, then everything will become clear to you right away!

This GET method is interesting! Change the address bar to something like this:

Http://lessons/index.php?user_name=My-name&user_year=1900&submit_form=submit

and press the "Enter" button. The server will answer you again, having already accepted other data! I think this is all clear.

The disadvantages of the GET method are that, firstly, there is a limit on the amount of data transferred, and secondly, this method is open and any information can be intercepted. That's why user personal data(login, name, password, etc.) can never be transmitted through the address line.

POST method

This method involves transmitting data in a separate packet stream in the body of the request, which reliably protects the sent data and allows you to transfer impressive amounts of information, which can only be limited by server settings. Therefore, this type of request is ideal for sending personal data and any types of files.

Edit your file by replacing the variable names $_GET with $_POST in the PHP code, and write method="POST" in the form. Refresh the page and submit the form again. The result will be the same as with the GET method, but the address bar remains unchanged, which means that the data was safely sent in a secure form in the body of the request itself.

To consolidate the material, we will create a small web application that will request the user’s login and password to enter the site. The example code will be relatively complex and requires your attention and desire to understand the functionality of the PHP program.

Index.php file:

Run the example and see what happens. First, the user's login and password are requested (in the code we defined them as “admin” and “secret”), if everything is correct, we are taken to the main page of the site, if the data is incorrect, a corresponding warning is displayed.

Let's consider the implementation of this technology.

Please note that we do not output the entire HTML form code directly, but store it in the $form variable.

Be careful with quotes! All HMTL code is inside single quotes, so its internal quotes must be double quotes. If you wrote

$form = "...your code...",

then the internal code will contain the opposite - single quotes.

Next, line 27 checks whether the form has been submitted (condition 1 in the figure), if not, the HTML form is displayed, and the script stops working– die() function. Nothing else except the form is displayed in the browser.

If the data has been received, then the POST variables are checked for compliance with the specified ones (condition 2 in the figure). If they do not match, a warning message is displayed, an HTML login form is displayed, and the script exits again (die()).

If the second condition is met, then the script skips all else statements and goes to displaying the main page. (transition 3 in Fig.).

This is the simplest example. Naturally, in real projects such direct checks are not performed - the login and password are stored in encrypted form in files or a database. Therefore, the article describes the technology of interaction between client and server based on GET and POST requests. To create full-fledged applications, you need to have a solid knowledge of databases and object-oriented programming. More on this in the following articles.

The content of the form is encoded exactly the same as for the method GET(see above), but instead of adding a line to URL the contents of the request are sent as a data block as part of the operation POST. If the ACTION attribute is present, then the value URL, which is there, determines where to send this block of data. This method, as already noted, is recommended for transferring large data blocks.

Information entered by user and submitted server using the method POST, is supplied to standard input to the program specified in the attribute action, or the current script if this attribute is omitted. The length of the sent file is transmitted in environment variable CONTENT_LENGTH, and the data type is in the CONTENT_TYPE variable.

Pass data using method POST is possible only with the help HTML forms, since the data is sent in the body of the request, and not in the header, as in GET. Accordingly, you can change the value of the parameters only by changing the value entered in the form. Using POST the user does not see the transmitted server data.

Main advantage POST requests is their greater security and functionality compared to GET requests. Therefore the method POST More often used to convey important information, as well as large-scale information. However, you should not rely entirely on the security of this mechanism, since the data POST The request can also be faked, for example by creating an html file on your machine and filling it with the necessary data. Moreover, not all clients can apply the method POST, which limits its use cases.

When sending data to server using any method, not only the data entered by the user is transmitted, but also a number of variables called environment variables, characterizing client, the history of its work, paths to files, etc. Here are some of environment variables:

    REMOTE_ADDR – IP address of the host (computer) sending the request;

    REMOTE_HOST – host name from which the request was sent;

    HTTP_REFERER – address of the page linking to the current script;

    REQUEST_METHOD – the method that was used when sending the request;

    QUERY_STRING – information contained in URL after the question mark;

    SCRIPT_NAME – virtual path to the program to be executed;

    HTTP_USER_AGENT – information about the browser that uses client

Handling requests using php

So far we have only mentioned that requests client processed at server using a special program. In fact, we can write this program ourselves, including in PHP, and it will do whatever we want with the received data. In order to write this program, you need to become familiar with some of the rules and tools offered for this purpose by PHP.

Within a PHP script there are several ways to access the data passed client according to the protocol HTTP. Before PHP 4.1.0, access to such data was carried out by the names of the transferred variables (remember that data is transferred in the form of pairs “variable name, “=” symbol, variable value”). Thus, if, for example, first_name=Nina was passed, then the $first_name variable with the value Nina appeared inside the script. If it was necessary to distinguish by what method the data was transmitted, then associative arrays were used $HTTP_POST_VARS And $HTTP_GET_VARS, the keys of which were the names of the transferred variables, and the values ​​were, respectively, the values ​​of these variables. Thus, if the pair first_name=Nina is passed by the method GET, then $HTTP_GET_VARS["first_name"]="Nina".

It is not safe to use the names of passed variables directly in a program. Therefore, it was decided, starting with PHP 4.1.0, to use a special array to access variables transmitted using HTTP requests - $_REQUEST. This array contains the data passed by the methods POST And GET, and also with the help HTTP cookies. This is a superglobal associative array, i.e. its values ​​can be obtained anywhere in the program using the name of the corresponding variable (form element) as a key.

Example 4.2. Let's say we created a form to register participants for a programming correspondence school, as in the example above. Then in file1.php that processes this form, you can write the following:

$str = "Hello,

".$_REQUEST["first_name"]. "

".$_REQUEST["last_name"]."!
";

$str .="You have chosen to study a course in

".$_REQUEST["kurs"];

Example 4.2. File1.php,processingformform.html(html , txt )

Then, if we entered the name “Vasya”, the surname “Petrov” into the form and selected the PHP course among all courses, we will receive the following message on the browser screen:

Hello, Vasya Petrov!

After introducing the array $_REQUEST arrays $HTTP_POST_VARS And $HTTP_GET_VARS for consistency were renamed to $_POST And $_GET respectively, but they themselves have not disappeared from use for reasons of compatibility with previous versions of PHP. Unlike their predecessors, arrays $_POST And $_GET have become super-global, i.e. accessible directly and inside functions and methods.

Let's give an example of using these arrays. Let's say we need to process a form containing input elements named first_name,last_name,kurs (for example, the form.html above). The data was transferred using the method POST, and we do not want to process data transmitted by other methods. This can be done as follows:

$str = "Hello,

".$_POST ["first_name"]."

".$_POST ["last_name"] ."!
";

$str .= "You have chosen to study a course on ".

Then on the browser screen, if we entered the name “Vasya”, the last name “Petrov” and selected the PHP course among all courses, we will see a message, as in the previous example:

Hello, Vasya Petrov!

You have chosen to study a PHP course

In order to maintain the ability to process scripts earlier than PHP 4.1.0, a directive was introduced register_globals, allowing or denying access to variables directly by their names. If the parameter register_globals=On in the PHP settings file, then the variables passed server methods GET And POST, you can simply contact them by their names (i.e. you can write $first_name). If register_globals=Off, then you need to write $_REQUEST["first_name"] or $_POST["first_name"], $_GET["first_name"], $HTTP_POST_VARS["first_name"], $HTTP_GET_VARS["first_name"]. From a security point of view, it is better to disable this directive (i.e. register_globals=Off). When the directive is enabled register_globals the arrays listed above will also contain the data passed client.

Sometimes there is a need to find out the meaning of some environment variable, such as the method used to transmit the request or the IP address of the computer that sent the request. You can obtain such information using the function getenv(). It returns a value environment variable, whose name is passed to it as a parameter.

getenv("REQUEST_METHOD");

// will return the method used

echo getenv("REMOTE_ADDR");

// will display the user's IP address,

// who sent the request

Example 4.3. Using the getenv() function (html , txt )

As we already said, if the method is used GET, then the data is transmitted by adding a query string in the form of pairs “variable_name=value to URL-resource address." Everything that is written in URL after the question mark, can be obtained using the command

getenv("QUERY_STRING");

Thanks to this method it is possible GET transmit data in some other form. For example, you can specify only the values ​​of several parameters using a plus sign, and in the script you can parse the query string into parts, or you can pass the value of just one parameter. In this case, in the array $_GET an empty element with a key equal to this value (the entire query string) will appear, and the “+” character encountered in the query string will be replaced by an underscore “_”.

Method POST data is transferred only using forms, and the user ( client) does not see what data is being sent server. To see them, the hacker must replace our form with his own. Then server will send the results of processing an incorrect form to the wrong place. To avoid this, you can check the address of the page from which the data was sent. This can be done again using the function getenv():

getenv("HTTP_REFERER");

Now is the time to solve the problem formulated at the beginning of the lecture.

PHP is currently one of the most popular languages ​​for implementing web applications. This course is devoted to studying its basics. The emphasis is on the practical application of acquired skills.

The PHP language was created to solve a specific practical problem on the Internet (which one can be found out by reading the first lecture of the course). We will also try not to be distracted too much by theoretical reasoning, and will strive to solve a specific problem in each of the lectures. Most of the examples are taken from a real-life system: a virtual museum of the history of computer science. The first part of the course is devoted to studying the basics of syntax and control structures. After this, client-server technology is considered as the main application area of ​​the PHP language. Then we move on to studying the most useful built-in functions in our opinion and solving practical problems with their help. Although the object model in the PHP language is not the richest, its fundamental presence allows you to naturally describe object data models. As a basic model, the document model of a virtual computer science museum will be considered. After this, a number of applied aspects will be considered: working with the file system, with the database, strings, sessions, DOM XML - all this will allow us to consider the key tasks of the practical use of the language.

As can be seen from the table above, the Apache server occupies a leading position. Everything we'll ever say about web servers is Apache-centric unless otherwise noted. We already talked about how to install it on your computer in the very first lecture. And now, as promised, let's turn to the HTTP protocol.

HTTP protocol and methods of transferring data to the server

The Internet is built on a multi-layered principle, from the physical layer, which deals with the physical aspects of transferring binary information, to the application layer, which provides the interface between the user and the network.

HTTP (HyperText Transfer Protocol) is an application layer protocol designed for exchanging hypertext information on the Internet.

HTTP provides a set of methods to specify the purpose of the request sent to the server. These methods are based on reference discipline, where a Universal Resource Identifier, either as a Universal Resource Locator (URL) or a Universal Resource Name, is used to indicate the resource to which the method should be applied. ,URN).

Messages over the network when using the HTTP protocol are transmitted in a format similar to the Internet mail message format (RFC-822) or to the MIME (Multipurpose Internet Mail Exchange) message format.

HTTP is used for communications between various user programs and gateway programs that provide access to existing Internet protocols such as SMTP (Email Protocol), NNTP (News Transfer Protocol), FTP (File Transfer Protocol), Gopher, and WAIS. HTTP is designed to allow such gateways to transfer data through proxy servers without loss.

The protocol implements the request/response principle. The requesting program - the client initiates interaction with the responding program - the server and sends a request containing:

Access method;

URI address;

Protocol version;

A message (similar in form to MIME) containing information about the type of data being transmitted, information about the client making the request, and possibly the content (body) of the message.

The server response contains:

A status line that includes the protocol version and the return code (success or error);

A message (in MIME-like form) that includes server information, meta information (that is, information about the contents of the message), and a message body.

The protocol does not specify who should open and close the connection between the client and server. In practice, the connection is usually opened by the client, and the server, after sending the response, initiates its termination.

Let's take a closer look at the form in which requests are sent to the server.

Customer Request Form

The client sends the request to the server in one of two forms: full or shortened. A request in the first form is called a full request, and in the second form a simple request.

A simple request contains an access method and a resource address. Formally, this can be written like this:

<Простой-Запрос> := <Метод> <символ пробел>
<Запрашиваемый-URI> <символ новой строки>

The method can be GET, POST, HEAD, PUT, DELETE and others. We will talk about the most common of them a little later. The requested URI is most often the URL of the resource.

Example of a simple request:

GET http://phpbook.info/

Here GET is the access method, i.e. a method that should be applied to the requested resource, and http://phpbook.info/ is the URL of the requested resource.

A complete request contains a status line, several headers (request header, general header, or content header), and possibly a request body. Formally, the general form of a complete request can be written as follows:

<Полный запрос> := <Строка Состояния>
(<Общий заголовок>|<Заголовок запроса>|
<Заголовок содержания>)
<символ новой строки>
[<содержание запроса>]

Square brackets here indicate optional header elements, and alternative options are listed through a vertical bar. Element<Строка состояния>contains the request method and resource URI (just like a simple request) and, in addition, the version of the HTTP protocol used. For example, to call an external program, you can use the following status line:

POST http://phpbook.info/cgi-bin/test HTTP/1.0

In this case, the POST method and HTTP version 1.0 are used.

In both forms of request, the URI of the requested resource plays an important role. Most commonly, a URI is used in the form of a resource URL. When accessing the server, you can use both the full form of the URL and the simplified one.

The full form contains the type of access protocol, the address of the resource server and the address of the resource on the server (Figure 4.2).

In the abbreviated form, the protocol and server address are omitted, indicating only the location of the resource from the server root. The full form is used if it is possible to forward the request to another server. If work occurs with only one server, then the abbreviated form is often used.


Rice. 4.2. Full URL form

Methods

As already mentioned, any client request to the server must begin with a method specification. The method communicates the purpose of the client's request. The HTTP protocol supports quite a few methods, but only three are actually used: POST, GET and HEAD. The GET method allows you to retrieve any data identified by the URI in the resource request. If the URI points to a program, then the result of the program's operation is returned, not its text (unless, of course, the text is the result of its operation). Additional information necessary to process the request is built into the request itself (in the status line). When using the GET method, the actual requested information (the text of an HTML document, for example) is returned in the resource body field.

There is a variation of the GET method - conditional GET. This method tells the server that the request should be answered only if the condition contained in the if-Modified-Since field of the request header is true. More specifically, the resource body is passed in response to the request if the resource has been modified since the date specified in if-Modified-Since.

The HEAD method is similar to the GET method, but does not return the resource body and does not have a conditional counterpart. The HEAD method is used to obtain information about a resource. This can be useful, for example, when solving the problem of testing hypertext links.

The POST method is designed to transfer information to the server such as resource annotations, news and mail messages, data to be added to the database, i.e. for transmitting large volume and quite important information. Unlike the GET and HEAD methods, POST passes the resource body, which is information received from form fields or other input sources.

Until now, we have only theorized and got acquainted with the basic concepts. Now it's time to learn how to use all this in practice. Later in the lecture we will look at how to send requests to the server and how to process its responses.

Using HTML Forms to Submit Data to the Server

How to transfer data to the server? For this purpose, the HTML language has a special construction - forms. Forms are designed to receive information from the user. For example, you need to know the user's login and password in order to determine which pages of the site he can be allowed to access. Or you need the user's personal data to be able to contact him. Forms are precisely used to enter such information. You can enter text in them or select appropriate options from a list. The data written in the form is sent for processing to a special program (for example, a PHP script) on the server. Depending on the data entered by the user, this program can generate various web pages, send queries to the database, launch various applications, etc.

Let's understand the syntax of HTML forms. Many may be familiar with it, but we will still repeat the main points because it is important.

So, to create a form in HTML, the FORM tag is used. Inside it is one or more INPUT commands. Using the action and method attributes of the FORM tag, you specify the name of the program that will process the form data and the request method, respectively. The INPUT command specifies the type and various characteristics of the information requested. The form data is sent after pressing the input button of the submit type. Let's create a form for registering participants in a correspondence school of programming.

Once processed by the browser, this file will look something like this:


Rice. 4.3. Example html form

This is how HTML forms are created and look like. We will assume that we have learned or remembered how to create them. As we can see, you can specify the data transfer method in the form. Let's see what happens if you specify the GET or POST method, and what the difference will be.

For the GET method

When submitting form data using the GET method, the form content is appended to the URL after the question mark as name=value pairs concatenated with an ampersand &:

action?name1=value1&name2=value2&name3=value3

Here action is the URL of the program that should process the form (either the program specified in the action attribute of the form tag, or the current program itself if that attribute is omitted). The names name1, name2, name3 correspond to the names of the form elements, and value1, value2, value3 correspond to the values ​​of these elements. All special characters, including = and &, will be omitted from these parameter names or values. Therefore, you should not use these symbols and Cyrillic characters in identifiers in the names or values ​​of form elements.

If you enter some service character in the input field, it will be transmitted in its hexadecimal code, for example, the $ symbol will be replaced by %24. Russian letters are also transmitted in the same way.

For text and password input fields (these are input elements with the type=text and type=password attribute), the value will be whatever the user enters. If the user does not enter anything into such a field, then the name= element will be present in the query string, where name corresponds to the name of this form element.

For checkbox and radio button buttons, the value is determined by the VALUE attribute when the button is checked. Unchecked buttons are ignored entirely when composing the query string. Multiple checkbox buttons can have the same NAME attribute (and different VALUEs) if necessary. Buttons of type radio button are intended for one of all offered options and therefore must have the same NAME attribute and different VALUE attributes.

In principle, it is not necessary to create an HTML form to transmit data using the GET method. You can simply add the desired variables and their values ​​to the URL string.

http://phpbook.info/test.php?id=10&user=pit

In this regard, data transmission using the GET method has one significant drawback - anyone can falsify parameter values. Therefore, we do not recommend using this method to access password-protected pages or to transmit information that affects the security of the program or server. In addition, you should not use the GET method to transfer information that the user is not allowed to change.

Despite all these disadvantages, using the GET method is quite convenient when debugging scripts (then you can see the values ​​and names of the variables being passed) and for passing parameters that do not affect security.

For POST method

The form content is encoded in exactly the same way as for the GET method (see above), but instead of adding a string to the URL, the request content is sent as a data block as part of the POST operation. If the ACTION attribute is present, then the URL value found there determines where to send this block of data. This method, as already noted, is recommended for transferring large data blocks.

Information entered by the user and sent to the server using the POST method is served on standard input to the program specified by the action attribute, or to the current script if this attribute is omitted. The length of the sent file is passed in the environment variable CONTENT_LENGTH, and the data type is passed in the CONTENT_TYPE variable.

You can only send data using the POST method using an HTML form, since the data is sent in the body of the request, and not in the header, as in GET. Accordingly, you can change the value of the parameters only by changing the value entered in the form. When using POST, the user does not see the data sent to the server.

The main advantage of POST requests is their greater security and functionality compared to GET requests. Therefore, the POST method is more often used to transmit important information, as well as large-scale information. However, you should not rely entirely on the security of this mechanism, since the POST request data can also be faked, for example, by creating an HTML file on your machine and filling it with the necessary data. Additionally, not all clients can use the POST method, which limits its use cases.

When sending data to the server by any method, not only the data entered by the user is transmitted, but also a number of variables, called environment variables, characterizing the client, its operation history, file paths, etc. Here are some of the environment variables:

REMOTE_ADDR – IP address of the host (computer) sending the request;

REMOTE_HOST – host name from which the request was sent;

HTTP_REFERER – address of the page linking to the current script;

REQUEST_METHOD – the method that was used when sending the request;

QUERY_STRING – information located in the URL after the question mark;

SCRIPT_NAME – virtual path to the program that should be executed;

HTTP_USER_AGENT – information about the browser that the client uses

So far, we have only mentioned that client requests are processed on the server using a special program. In fact, we can write this program ourselves, including in PHP, and it will do whatever we want with the received data. In order to write this program, you need to become familiar with some of the rules and tools that PHP offers for this purpose.

Within a PHP script, there are several ways to access data sent by a client via HTTP. Before PHP 4.1.0, access to such data was carried out by the names of the transferred variables (remember that data is transferred in the form of pairs “variable name, “=” symbol, variable value”). Thus, if, for example, first_name=Nina was passed, then the $first_name variable with the value Nina appeared inside the script. If it was necessary to distinguish by what method the data was transferred, then the associative arrays $HTTP_POST_VARS and $HTTP_GET_VARS were used, the keys of which were the names of the transferred variables, and the values ​​were, respectively, the values ​​of these variables. Thus, if the pair first_name=Nina is passed by the GET method, then $HTTP_GET_VARS["first_name"]="Nina".

It is not safe to use the names of passed variables directly in a program. Therefore, it was decided, starting with PHP 4.1.0, to use a special array – $_REQUEST – to access variables transmitted via HTTP requests. This array contains data transferred using the POST and GET methods, as well as using HTTP cookies. This is a superglobal associative array, i.e. its values ​​can be obtained anywhere in the program using the name of the corresponding variable (form element) as a key.

Example 4.2. Let's say we created a form to register participants for a programming correspondence school, as in the example above. Then in the 1.php file that processes this form, you can write the following:

$str = "Hello,
".$_REQUEST["first_name"]. "
".$_REQUEST["last_name"]."!
";
$str .="You have chosen to study a course in
".$_REQUEST["kurs"];
echo $str;
?>

Then, if we entered the name “Vasya”, the surname “Petrov” into the form and selected the PHP course among all courses, we will receive the following message on the browser screen:

Hello, Vasya Petrov!

After the introduction of the $_REQUEST array, the $HTTP_POST_VARS and $HTTP_GET_VARS arrays were renamed $_POST and $_GET, respectively, for consistency, but they themselves did not disappear from use for reasons of compatibility with previous versions of PHP. Unlike their predecessors, the $_POST and $_GET arrays have become super-global, i.e. accessible directly and inside functions and methods.

Let's give an example of using these arrays. Let's say we need to process a form containing input elements named first_name, last_name, kurs (for example, the form.html above). The data was transferred using the POST method, and we do not want to process data transferred by other methods. This can be done as follows:

$str = "Hello,
".$_POST ["first_name"]."
".$_POST ["last_name"] ."!
";
$str .= "You have chosen to study a course on ".
$_POST["kurs"];
echo $str;
?>

Then on the browser screen, if we entered the name “Vasya”, the last name “Petrov” and selected the PHP course among all courses, we will see a message, as in the previous example:

Hello, Vasya Petrov!
You have chosen to study a PHP course

In order to maintain the ability to process scripts earlier than PHP 4.1.0, the register_globals directive was introduced, allowing or denying access to variables directly by their names. If the register_globals=On parameter is in the PHP settings file, then variables passed to the server using the GET and POST methods can be accessed simply by their names (i.e. you can write $first_name). If register_globals=Off, then you need to write $_REQUEST["first_name"] or $_POST["first_name"], $_GET["first_name"], $HTTP_POST_VARS["first_name"], $HTTP_GET_VARS["first_name"]. From a security point of view, it is better to disable this directive (i.e. register_globals=Off). With the register_globals directive enabled, the arrays listed above will also contain the data passed by the client.

Sometimes you need to know the value of an environment variable, such as the method used to send the request or the IP address of the computer that sent the request. You can get this information using the getenv() function. It returns the value of the environment variable whose name is passed to it as a parameter.

getenv("REQUEST_METHOD");
// will return the method used
echo getenv("REMOTE_ADDR");
// will display the user's IP address,
// who sent the request
?>

As we have already said, if the GET method is used, then the data is transferred by adding a query string in the form of variable_name=value pairs to the resource URL. Anything after the question mark in the URL can be retrieved using the command

getenv("QUERY_STRING");

Thanks to this, it is possible to transfer data in some other form using the GET method. For example, you can specify only the values ​​of several parameters using a plus sign, and in the script you can parse the query string into parts, or you can pass the value of just one parameter. In this case, an empty element with a key equal to this value (the entire query string) will appear in the $_GET array, and the “+” character encountered in the query string will be replaced with an underscore “_”.

With the POST method, data is transmitted only using forms, and the user (client) does not see what data is sent to the server. To see them, the hacker must replace our form with his own. Then the server will send the results of processing the incorrect form to the wrong place. To avoid this, you can check the address of the page from which the data was sent. This can be done again using the getenv() function:

getenv("HTTP_REFERER");

Now is the time to solve the problem formulated at the beginning of the lecture.

Example of processing a request using PHP

Let us recall what the task was and clarify its formulation. You need to write a form to register participants in the correspondence school of programming and after registration send a message to the participant. We have called this message the universal letter, but it will be slightly different from the letter we composed in the previous lecture. Here we will also not send anything by email, so as not to be like spammers, but will simply generate this message and display it on the browser screen. We have already provided the initial version of the registration form above. We will change it so that each registrar can choose as many courses as they want to attend, and we will not confirm receipt of the registration form.

Everything here is quite simple and clear. The only thing to note is the way the values ​​of the checkbox element are passed. When we write kurs in the element name, this means that the first checked checkbox element will be written to the first element of the kurs array, the second checked checkbox will be written to the second array element, etc. You can, of course, simply give different names to the checkbox elements, but this will complicate data processing if there are many courses.

The script that will parse and process all this is called 1.php (the form refers specifically to this file, which is written in its action attribute). By default, the GET method is used for transmission, but we specified POST. Based on the information received from the registered person, the script generates a corresponding message. If a person has chosen some courses, he will receive a message about the time they will be held and the lecturers who teach them. If a person has not selected anything, then a message about the next meeting of the Correspondence School of Programmers (CSS) is displayed.