15.08.2023

Browser and server interaction on the example of GET and POST requests. Form processing. PHP GET and POST methods, $_REQUEST variable Handling php http requests


For the POST method

The form content is encoded in 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 supplied as standard input to the program specified in the action attribute, or to the current script if this attribute is omitted. The length of the uploaded file is passed in the CONTENT_LENGTH environment variable, 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 transmitted 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 transmitted 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 transfer important information, as well as information of a large amount. However, you should not rely entirely on the security of this mechanism, since POST request data can also be faked, for example, by creating an html file on your machine and filling it with the necessary data. Also, 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 that characterize the client, its history, file paths, etc. Here are some of the environment variables:

  • REMOTE_ADDR – IP address of the host (computer) sending the request;
  • REMOTE_HOST - hostname from which the request was sent;
  • HTTP_REFERER - address of the page referring to the current script;
  • REQUEST_METHOD - the method that was used when sending the request;
  • QUERY_STRING - information found in the URL after the question mark;
  • SCRIPT_NAME - virtual path to the program to be executed;
  • HTTP_USER_AGENT - Information about the browser the client is using

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 get acquainted with some of the rules and tools offered for this purpose by PHP.



Within a PHP script, there are several ways to access data sent by a client over HTTP. Prior to PHP 4.1.0, access to such data was carried out by the names of the passed variables (recall that data is passed in the form of “variable name, “=” symbol, variable value” pairs). 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 the values ​​of these variables, respectively. Thus, if the pair first_name=Nina is passed by the GET method, then $HTTP_GET_VARS["first_name"]="Nina".

It is unsafe to use the names of the passed variables directly in the program. Therefore, starting with PHP 4.1.0, it was decided to use a special array - $_REQUEST - to access variables passed via HTTP requests. This array contains the data transmitted by the POST and GET methods, as well as via HTTP cookies. This is a super-global 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 for registering participants in a correspondence programming 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 the course on ".$_REQUEST["kurs"];echo $str;?>

Then, if we entered the name "Vasya" in the form, the surname "Petrov" and chose 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 to $_POST and $_GET, respectively, for uniformity, but they themselves have not disappeared from use for reasons of compatibility with previous versions of PHP. Unlike their predecessors, the $_POST and $_GET arrays have become superglobal, i.e. accessible directly and within 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 form 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 like this:

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

Then on the browser screen, if we entered the name "Vasya", the surname "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 the PHP course

In order to preserve 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 in the PHP settings file, then variables passed to the server by 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 (ie register_globals=Off). With the register_globals directive enabled, the arrays listed above will also contain data submitted 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 already said, if the GET method is used, then the data is transmitted by adding a query string in the form of "variable_name = value" pairs to the resource URL. Everything that is written in the URL after the question mark can be obtained 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, specify only the values ​​of several parameters separated by a plus sign, and parse the query string into parts in the script, 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 “+” symbol found 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 kind of 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 wrong 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 with the getenv() function:

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 focuses on learning its basics. The emphasis is on the practical application of acquired skills.

The PHP language was created to solve a specific practical problem in the Internet environment (which one can be found out after reading the first lecture of the course). We will also try not to be distracted too much by theoretical considerations, and we will strive to solve a specific problem in each of the lectures. Most of the examples are taken from a real-life system: the virtual museum of the history of computer science. The first part of the course is devoted to learning the basics of syntax and control structures. After that, client-server technology is considered as the main area of ​​application of the PHP language. Then we turn to the study of the most useful built-in functions in our opinion and solving practical problems with their help. Although the object model in PHP is not the richest, its fundamental presence allows you to describe object data models in a natural way. As a basic model, the document model of the virtual museum of informatics will be considered. After that, 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 above table, the Apache server occupies a leading position. Everything we'll ever talk about web servers is Apache oriented 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-layer 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 for specifying the purposes of a request sent to a server. These methods are based on the discipline of links, where the Universal Resource Identifier is used in the form of the resource location (Universal Resource Locator, URL) or in the form of its universal name (Universal Resource Name) to specify the resource to which this method should be applied. , URN).

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

HTTP is used for communication 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 transmit lossless data through middleware servers (proxy).

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) with information about the type of data being transferred, information about the client that sent the request, and possibly the content (body) of the message.

The server response contains:

Status line, which includes the protocol version and the return code (success or error);

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

The protocol does not specify who should open and close the connection between the client and the server. In practice, the connection, as a rule, is 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 a request to the server in one of two forms: full or abbreviated. The request in the first form is called, respectively, a complete 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 as follows:

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

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

An example of a simple request:

GET http://phpbook.info/

Here GET is the access method, i.e. the method to 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 (a request header, a general header, or a content header), and optionally a request body. Formally, the general form of the complete query can be written as follows:

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

Square brackets denote optional heading elements here, alternatives are listed through the vertical bar. Element<Строка состояния>contains the request method and resource URI (just like a simple request) and, in addition, the version of the HTTP protocol to use. 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 protocol version 1.0 are used.

In both forms of the request, the URI of the requested resource is prominent. The most common use of a URI is 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 access protocol type, resource server address, and resource address on the server (Figure 4.2).

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


Rice. 4.2. Full form URL

Methods

As already mentioned, any request from the client to the server must begin with a method specification. The method reports 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 get any data identified by the URI in the resource request. If the URI points to a program, then the result of the program is returned, not its text (unless, of course, the text is the result of its work). Additional information needed to process the request is embedded in 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, the conditional GET. This method tells the server that the request should only be answered if the condition contained in the if-Modified-Since field of the request header is met. More specifically, the body of a resource is passed in response to a request if that resource has been modified since the date specified in if-Modified-Since.

The HEAD method is similar to the GET method except that it does not return a resource body and has no conditional counterpart. The HEAD method is used to get information about a resource. This can be useful, for example, when solving the problem of testing hypertext links.

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

Until now, we have only theorized, 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 send data to the server? To do this, HTML has a special construction - forms. Forms are designed to receive information from the user. For example, you need to know the username and password of the user 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 just used to enter such information. You can enter text in them or select the appropriate options from the list. The data entered in the form is sent to a special program (for example, a PHP script) on the server for processing. 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. Perhaps many are familiar with it, but we will still repeat the main points, since this is important.

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

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


Rice. 4.3. html form example

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 will happen if you specify the GET or POST method, and what will be the difference.

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

Where 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 this 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 &, in the names or values ​​of these parameters will be omitted. Therefore, you should not use these symbols in the names or values ​​of form elements and Cyrillic symbols in identifiers.

If you enter any 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.

For text and password input fields (these are input elements with type=text and type=password attributes), 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 completely ignored when compiling a query string. Multiple checkbox buttons can have the same NAME attribute (and different VALUEs) if needed. Buttons of type radio button are designed for one of all the proposed options and therefore must have the same NAME attribute and different VALUE attributes.

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

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

In this regard, the transmission of data by the GET method has one significant drawback - anyone can fake parameter values. Therefore, we do not recommend using this method to access password-protected pages, to transfer information that affects the security of the program or server. Also, don't use the GET method to pass information that the user isn't allowed to change.

Despite all these shortcomings, 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 the POST method

The form content is encoded in 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 supplied as standard input to the program specified in the action attribute, or to the current script if this attribute is omitted. The length of the uploaded file is passed in the CONTENT_LENGTH environment variable, 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 transmitted 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 transmitted 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 transfer important information, as well as information of a large amount. However, you should not rely entirely on the security of this mechanism, since POST request data can also be faked, for example, by creating an html file on your machine and filling it with the necessary data. Also, 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 that characterize the client, its history, file paths, etc. Here are some of the environment variables:

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

REMOTE_HOST - hostname from which the request was sent;

HTTP_REFERER - address of the page referring to the current script;

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

QUERY_STRING - information found in the URL after the question mark;

SCRIPT_NAME - virtual path to the program to be executed;

HTTP_USER_AGENT - Information about the browser the client is using

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 get acquainted with some of the rules and tools offered for this purpose by PHP.

Within a PHP script, there are several ways to access data sent by a client over HTTP. Prior to PHP 4.1.0, access to such data was carried out by the names of the passed variables (recall that data is passed in the form of “variable name, symbol “=”, variable value” pairs). 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 the values ​​of these variables, respectively. Thus, if the pair first_name=Nina is passed by the GET method, then $HTTP_GET_VARS["first_name"]="Nina".

It is unsafe to use the names of the passed variables directly in the program. Therefore, starting with PHP 4.1.0, it was decided to use a special array - $_REQUEST - to access variables passed via HTTP requests. This array contains the data transmitted by the POST and GET methods, as well as via HTTP cookies. This is a super-global 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 for registering participants in a correspondence programming 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 selected a course in
".$_REQUEST["kurs"];
echo $str;
?>

Then, if we entered the name "Vasya" in the form, the surname "Petrov" and chose 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 to $_POST and $_GET, respectively, for uniformity, but they themselves have not disappeared from use for reasons of compatibility with previous versions of PHP. Unlike their predecessors, the $_POST and $_GET arrays have become superglobal, i.e. accessible directly and within 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 form 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 like this:

$str = "Hello,
".$_POST ["first_name"]."
".$_POST ["last_name"] ."!
";
$str .= "You have selected a course in ".
$_POST["kurs"];
echo $str;
?>

Then on the browser screen, if we entered the name "Vasya", the surname "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 the PHP course

In order to preserve 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 in the PHP settings file, then variables passed to the server by 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 (ie register_globals=Off). With the register_globals directive enabled, the arrays listed above will also contain data submitted 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");
// return the used method
echo getenv("REMOTE_ADDR");
// will display the user's IP address,
// who sent the request
?>

As we already said, if the GET method is used, then the data is transmitted by adding a query string in the form of "variable_name = value" pairs to the resource URL. Everything that is written in the URL after the question mark can be obtained 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, specify only the values ​​of several parameters separated by a plus sign, and parse the query string into parts in the script, 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 “+” symbol found 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 kind of 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 wrong 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 with the getenv() function:

getenv("HTTP_REFERER");

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

PHP Request Handling Example

Let us recall what the problem was and clarify its formulation. You need to write a form for registering participants in the correspondence school of programming and send a message to the participant after registration. 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 e-mail, so as not to be like spammers, but simply generate this message and display it on the browser screen. We have already given the initial version of the registration form above. We will change it so that each registrant 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 name of an element, it means that the first checked checkbox element will be written to the first element of the kurs array, the second checked checkbox to the second element of the array, and so on. You can, of course, just give different names to the checkbox elements, but this will complicate data processing if there are a lot of courses.

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

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 with 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 sensitive information to send to the server.
  • GET cannot be used to send binary data, such as images or text documents, to a 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.

This and the following sections will briefly show you how to create simple web applications using PHP. What was described in the section is clearly not enough for your application to communicate with the user and form depending on the actions performed by him or the parameters entered by him. And what is missing? There is a lack of knowledge on how to organize user input and transfer this data to the server. Well, you should already have basic knowledge of how to programmatically process information received on the server.

HTTP request methods and their parameters

Any dynamic web application generates a response to the user in accordance with the parameters entered by him or the actions performed on the client side. The request to the server most often comes down to two types of requests: using the GET method or the POST method. A few words about the differences between these two types of requests.

GET method:

    The parameters are passed in the HTTP request header, so they are visible on the command line, and such a request can be bookmarked. Since the total length of the header is limited, the number and length of parameters passed using GET is also limited.

    It is believed that the results of several identical GET requests executed in a row should be the same.

POST method:

    Request parameters are passed in the body of the HTTP request, so they are not on the command line. The number and size of parameters is unlimited.

    It is considered that the results of several identical POST requests may return different values, since they may change the properties of the target object.

The GET method should be used to retrieve the contents of an information resource according to the parameters, when it is not necessary to make changes to the data structures of the target resource, and it makes sense to bookmark the request (URL). The execution speed of the GET method may be faster than similar requests using the POST method.

The POST method should be used when it is necessary to hide the parameters passed to the server from the URL. This method should also be used in requests for changes to the contents of the target resource, passing in the parameters (in the body of the request) a description of these same changes.

Path to resource? parameter1=value1¶meter2=value2&…

If you do not have a special HTML form to fill in parameters, then you can debug your PHP application by passing test parameters directly on the browser command line, for example:

http://website/php-samples/sql.php?sql=select * from d_staff

To access query parameters on the server side, use global arrays $_GET And $_POST respectively. If your application doesn't care what method it was accessed with, then you should use an array $_REQUEST, which combines the data of the $_GET and $_POST arrays, for example, like this:

$sql = isset($_REQUEST["sql"]) ? $_REQUEST["sql"] : "";

In this example, the program determines whether the "sql" parameter was passed: if so, it assigns its value to the corresponding variable, and if not, it assigns an empty value to it.

Defining HTTP request parameters via HTML form

Of course, it is not very convenient to define parameters manually directly in the browser command line. This method is suitable for programmatic execution of HTTP requests when communicating between web applications. In order to enter and perform initial data validation on the client side, you should use HTML forms and . Below is an example of the simplest form, with the help of which a text parameter (value ) is entered, which is subsequently passed to the server as a parameter of the POST method.

method ="post" action ='sql.php' > SQL:

The method attribute of the form element specifies the method that determines how data is sent to the server (get or post). The action attribute specifies php file The one that will process the request. If the handler should be the current file, then the action attribute does not need to be added. For all elements whose value is to be passed as an HTTP request parameter, a unique value for the name attribute should be defined. It is the value of the attribute name will be index in $_GET, $_POST or $_REQUEST arrays (see example above). Clicking on a button submit submits the form with all entered values ​​to the server.

The content of the form is encoded in the same way as for the method GET(see above), but instead of adding a line to URL the content of the request is 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 the user and submitted server using the method POST, is supplied as standard input to the program specified in the attribute action, or the current script if this attribute is omitted. The length of the file being sent is sent to environment variable CONTENT_LENGTH and the data type is in the CONTENT_TYPE variable.

Pass data by method POST possible only with HTML Forms, because the data is passed in the body of the request, 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 often used to convey important information, as well as information of a large volume. However, you should not rely entirely on the security of this mechanism, since the data POST requests 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 use the method POST which limits its use cases.

When sending data to server any method transmits not only the data itself entered by the user, 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 – name of the host from which the request was sent;

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

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

    QUERY_STRING - information 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 with php

So far, we have only mentioned that requests client processed on 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 get acquainted 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 protocol http. Prior to PHP 4.1.0, access to such data was carried out by the names of the passed variables (recall that data is passed in the form of “variable name, symbol “=”, variable value” pairs). 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 required to distinguish by what method the data was transferred, then associative arrays were used $HTTP_POST_VARS And $HTTP_GET_VARS, whose keys were the names of the passed variables, and the values ​​were the values ​​of these variables, respectively. Thus, if the pair first_name=Nina is passed to the method GET, then $HTTP_GET_VARS["first_name"]="Nina".

It is unsafe to use the names of the passed variables directly in the program. Therefore, it was decided, starting from PHP 4.1.0, to use a special array to access variables transmitted via HTTP requests - $_REQUEST. This array contains the data passed by the methods POST And GET, as well as using http cookies. This is a super-global 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 for registering participants in a correspondence programming 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 selected a course in

".$_REQUEST["kurs"];

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

Then, if we entered the name "Vasya" in the form, the surname "Petrov" and chose the PHP course among all courses, we will receive the following message on the browser screen:

Hello Vasya Petrov!

After introducing an array $_REQUEST arrays $HTTP_POST_VARS And $HTTP_GET_VARS renamed for consistency $_POST And $_GET respectively, but they themselves have not disappeared from use for reasons of compatibility with previous versions of PHP. Unlike its predecessors, arrays $_POST And $_GET have become superglobal, i.e. accessible directly and within functions and methods.

Let's give an example of using these arrays. Let's say we need to process a form that contains input elements named first_name,last_name,kurs (for example, the form.html form above). The data was transferred using the method POST, and we don't want to process the data passed by other methods. This can be done like this:

$str = "Hello,

".$_POST ["first_name"]."

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

$str .= "You have selected a course in ".

Then on the browser screen, if we entered the name "Vasya", the surname "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 the PHP course

In order to preserve the ability to process scripts earlier than PHP 4.1.0, the directive register_globals, allowing or denying access to variables directly by their names. If in the PHP settings file the parameter register_globals=On, then to the variables passed server methods GET And POST, you can refer to them 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 (ie register_globals=Off). When the directive is enabled register_globals the arrays listed above will also contain the data passed client.

Sometimes it becomes necessary to know the meaning of some 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 function getenv(). It returns a value environment variable, whose name is passed to it as a parameter.

getenv("REQUEST_METHOD");

// return the used method

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 have 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 recorded in URL after the question mark, can be obtained using the command

getenv("QUERY_STRING");

Thanks to this, it is possible, according to the method GET transfer data in some other form. For example, specify only the values ​​of several parameters separated by a plus sign, and parse the query string into parts in the script, 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 with an underscore "_".

method POST data is only submitted using forms, and the user ( client) does not see exactly 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 the wrong 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.


2023
maccase.ru - Android. Brands. Iron. News