We process POST requests in PHP. NodeJS. How to process POST requests Processing http requests php

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 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 secure.
  • 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.

The first method to perform a PHP POST request is to use file_get_contents . The second method will use fread in combination with a couple of other functions. Both options use the stream_context_create function to fill in the required request header fields.

Code Explanation

The $sPD variable contains the data to be transferred. It must be in HTTP request string format, so some special characters must be encoded.

In both the file_get_contents function and the fread function we have two new parameters. The first one is use_include_path . Since we are making an HTTP request, it will be false in both examples. When set to true to read a local resource, the function will look for the file at include_path .

The second parameter is context, which is populated with the return value of stream_context_create, which takes the value of the $aHTTP array.

Using file_get_contents to make POST requests

To send a POST request using file_get_contents in PHP, you need to use stream_context_create to manually fill out the header fields and specify which "wrapper" to use - in this case HTTP:

$sURL = "http://brugbart.com/Examples/http-post.php"; // POST URL $sPD = "name=Jacob&bench=150"; // POST data $aHTTP = array("http" => // Wrapper that will be used array("method" => "POST", // Request method // Request headers are set below "header" => "Content- type: application/x-www-form-urlencoded", "content" => $sPD)); $context = stream_context_create($aHTTP); $contents = file_get_contents($sURL, false, $context); echo $contents;

Using fread to perform POST requests

You can use the fread function to make POST requests. The following example uses stream_context_create to compose the necessary HTTP request headers:

$sURL = "http://brugbart.com/Examples/http-post.php"; // POST URL $sPD = "name=Jacob&bench=150"; // POST data $aHTTP = array("http" => // Wrapper that will be used array("method" => "POST", // Request Method // Request headers are set below "header" => "Content- type: application/x-www-form-urlencoded", "content" => $sPD)); $context = stream_context_create($aHTTP); $handle = fopen($sURL, "r", false, $context); $contents = ""; while (!feof($handle)) ( $contents .= fread($handle, 8192); ) fclose($handle); echo $contents;

Making GET Requests with PHP

We will now focus on using fread and file_get_contents to download content from the internet via HTTP and HTTPS. To use the methods described in this article, you must enable the fopen wrappers option. To do this, you need to set the allow_url_fopen parameter to On in the php.ini file.

Performing POST and GET requests in PHP is used to log into websites, retrieve web page content, or check for new versions of applications. We'll cover how to make simple HTTP requests.

Using fread to download or receive files over the Internet

Remember that web page reading is limited to the accessible portion of the packet. So you need to use the function stream_get_contents ( similar to file_get_contents) or a while loop to read the contents in smaller chunks until the end of the file is reached:

In this case of processing a PHP POST request, the last argument of the fread function is equal to the fragment size. It should generally not be greater than 8192 ( 8*1024 ).

Keep in mind that it may be larger or smaller, and may also be limited by the settings of the system on which PHP is running.

Using file_get_contents to get a site's URL

It's even easier to use this method when reading a file over HTTP, since you don't have to worry about reading in chunks - everything is handled in PHP.

This publication is a translation of the article “Making POST Requests With PHP”, prepared by the friendly project team

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 the transfer of 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 the 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. The most common 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 transfers 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 block of data 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 (ZSH) is displayed.

HTML forms allow user-entered data to be sent to a server, where it can be further processed. Form maintenance is performed in two stages. The form must first be presented to the user, who will fill it with their data and then submit it to the server. Each form has a landing web page that must be loaded to process the data submitted by the user. This is often the same script file that generates the form. In this case, the PHP code simply checks for data in the form to determine whether to call the script again to create the form or begin processing the received data.

Attention! The lesson is outdated. New lessons on this topic are contained in the PHP for Beginners course.

In most cases, submitting forms to the server involves some kind of database work. For example, a database search operation is a necessary action for most diverse applications, be it searching forum posts, users, or a blog. In any case, this operation can make the user's life easier. Because At this point, we have not yet become acquainted with the interaction of PHP and the MySQL DBMS, in this article we will look at simple examples of form processing, and the main task for me is to show how information is transferred using the PHP language.

Transferring information using PHP language

This section provides basic information about how data can be transferred between web pages. Some of this information does not relate exclusively to PHP technology, but describes the interaction of PHP and HTML tools or concerns the HTTP protocol itself.

Lack of state support in HTTP protocol

The most important feature of any web technology that should always be kept in mind is that the HTTP protocol itself is stateless. This means that each HTTP request (which in most cases amounts to a request to receive and deliver a single resource, such as an HTML page, a .jpg file, a style sheet, etc.) is independent of all other requests, does not include any - information about the client’s identification and does not leave a trace in the computer’s memory.

Even if the site is designed in such a way that the navigation, i.e. transition from one page to another occurs strictly in one direction (let's say page 1 leads only to page 2, which leads only to page 3, etc.), HTTP protocol support tools do not have information and do not take into account that a user viewing page 2 must have previously visited page 1. You cannot assign a value to a variable on page 1 and expect it to be imported into page 2 using HTML itself. HTML code can be used to display a form, and this code can even be used to enter information, but unless some additional means is used to transfer the entered information to another page or program, the value assigned to the variable will simply disappear after moving to another page .

Form processing technologies like PHP are designed to solve exactly this problem. PHP allows you to intercept the value of a variable being passed from the previous page to the next and make that value available for later use. As it turns out, PHP technology provides the ability to perform these types of data transfer functions extremely well, so it allows you to quickly and easily deploy the necessary tools to solve a wide variety of problems associated with ensuring the functioning of a website.

HTML forms provide a convenient way to pass a small number of values ​​from a given page to any other single page on a website. There are other ways to maintain state across many page views that are longer lasting, such as cookies and sessions, which will be covered in a future article. This article focuses mainly on the simplest ways to transfer information between web pages, which use GET and POST methods in combination with the HTTP protocol to create dynamically generated pages and process form data.

GET parameters

The GET method passes parameters from the previous page to the next as part of a query string, which is represented in the format of a Uniform Resource Identifier URI. When you use the GET method to process a form, the URL identified by the form's action attribute is followed by a question mark after the delimiter, followed by the specified variable name(s) and value(s), and then the entire string is passed to the processing agent (in this case, the web server).

Below is an example of an HTML form that uses the GET method (type this markup and save the file as sportselect.html):

PHP Basics

Choose your favorite sport

Once the user makes their selection and clicks the Submit button, the browser will connect the following elements in the order shown, with no spaces between elements:

  • URL in quotes after the word action (http://localhost/sports.php).
  • A question mark (?) indicating that the following characters make up a GET string.
  • The name variable, the equal sign (=) and the corresponding value parameter (value=Hockey).
  • The ampersand (&) followed by the name=value pair (if any).

So the browser will generate the following URL string:
http://localhost/sports.php?sport=Hockey

The browser then redirects the resulting URL string within its own address space as a new request. The PHP script below (sports.php), to which the form is submitted, fetches the GET variable values ​​from the last part of the query string, inserts those variables and variable values ​​into the $_GET superglobal array (to be described shortly), and performs some necessary actions with these values; in this case, the insertion occurs in a text string.

Below is a code example that shows the PHP form handler for the above HTML form:

Favorite sport

Your favorite sport is

Note that the value entered into the HTML form field with the name="sport" attribute on the previous page is now available as a PHP variable named $_GET["sport"]. The following figure demonstrates how this example works:

Now we need to explain exactly how you can access the values ​​passed from page to page. This article discusses the two main methods of passing values ​​used in forms - GET and POST. Each method has a superglobal array associated with it. Superglobal arrays are described in more detail in the article "Variables and Constants". A distinctive feature of superglobal arrays from other arrays is the presence of a prefix in the name in the form of an underscore.

The form processor accesses each element submitted using the GET method by accessing the $_GET array, and each element submitted using the POST method by accessing the $_POST array. The syntactic structure used to access any element of a superglobal array is simple and completely uniform:

$_array_name["index_name"]

Here, index_name is the name portion of the name-value pair (for the GET method), or the name of the HTML form field (for the POST method). Following the previous example, $_GET["sport"] specifies the value of the select element of the form named "sport"; this value was passed using a GET operation performed on the original file. The form handler must use an array corresponding to the method by which the data was submitted. Specifically, in this example, the value of $_POST["sport"] is undefined because the original form did not submit any data using the POST method.

The GET form processing method has one significant advantage over the POST method - it actually allows you to generate a new URL query string each time, appropriate to the current situation. Users can then bookmark this page. On the other hand, the results of form submissions using the POST method cannot be bookmarked.

Just because the desired functionality can be achieved using GET parameters does not mean that the GET method must be used. The disadvantages of the GET method that are found in most types of form processing are so significant. The original HTML 4.0 working specification, published in 1997, did not recommend this method. The main disadvantages of the GET method are listed below:

  • The GET method is not applicable to creating registration windows, since the username and password are completely visible on the screen, and it is also possible that this data is stored in the memory of the client's browser as information about the page visited.
  • Each GET transfer operation, including the data set itself, is logged on the web server.
  • The GET method assigns data to a server environment variable, so the length of the URL is limited. You may have seen what very long URLs look like when passed using the GET method, and indeed, it is unlikely that anyone would want to send a 300-word piece of HTML text using this method.

The original HTML specification stated that the length of the query string should not exceed 255 characters. Of course, this restriction was later removed and only the recommendation remained to adhere to the 255 character limit, but the use of longer lines can still cause disruption.

POST parameters

Currently, the preferred method for submitting form data is POST (especially in cases where performing actions results in permanent changes, such as entering information into a database). The form data set is included in the form body when the form is redirected to the processing agent (in this case, the PHP interpreter). The URL string does not undergo any visible changes to reflect the variety of data being transferred.

There is a widespread unjustified belief among developers that the POST method is more secure than GET. In reality, neither method is more or less secure than the other. A visitor can view variables and data sent using the POST method just as well as using the GET method. The only difference is that in the first case, the transmitted data is not found in the address bar. But this does not mean that they are hidden. Data sent using the POST method can be viewed and modified by the website user.

The first and most important rule of programming, especially network programming, is this:
Never trust input data.

You should always assume that a visitor may have maliciously, or even accidentally, changed the data being passed to a particular application, so you need to carefully check that data.

The transmitted form data is only more or less secure if the request is secured using SSL, TLS, or some other encryption method. But the data still arrives to the end user or visitor in clear form, so he still has the opportunity to view and change the data in one way or another. The fact is that the SSL protocol simply encrypts data transmitted over the network, which does not allow the data to be viewed in clear text at the stage of its passage from the sender to the recipient. As for the ability for a visitor to make changes to form data, the SSL protocol does not provide anything to prevent this.

To change the way data is transferred in the previous example, you need to make the following changes:

...

Working with Multiple Values

If the form has checkboxes or radio buttons, a new problem arises. For example, a user can select two values ​​at once in a form, but a variable cannot store more than one value, so an array will have to be used. This situation is demonstrated in the example below:

" method="post">
Choose your favorite pets

Animals selected: "; foreach ($animal as $a) ( echo " ".htmlentities($a).""; } } ?>

This form allows the user to select their favorite pets. In this example, the user can select several checkboxes at once. This means that when processing form data in a PHP script, it is necessary to provide the ability to access multiple values ​​using one name. We've placed a pair of square brackets () after the name in the name attribute to be able to send multiple choices as an array. If the square brackets were omitted and the user checked multiple checkboxes, their selection would be overwritten by the last checked checkbox. By placing square brackets after the name, we indicated that the values ​​should be stored as an array.

In the handler, the array is stored in the $animal variable and enumerated using a foreach loop, like a regular array.

Form Validation and Formatting Form Variables

When an application receives data from a user, it must check it for correctness each time. If you do not check the data entered by the user, you can get many problems, including security risks. Performing a background check is not as difficult as it may seem.

It is more convenient for users to check on the client side using JavaScript, but regardless of whether this check is used, server-side verification must be performed.

Another thing to consider when creating HTML forms is that if the form needs to display pre-filled input, then the value attribute must be set. This point is especially true of two types of forms - those that are used to edit data received from a database, and those that are designed to possibly submit data more than once. The latter case is very common in situations where the form must be re-displayed after errors are detected in the data already filled out in advance. An example would be a registration form that does not accept data for processing until the user provides a valid email address or other required data.

The example below shows how to process a form, including server-side validation and processing on the same form page:

PHP Basics

" method="post">
Contact Information "class="">
"class="">

This example uses the filter_var() function, which tests a variable using a filter and takes two parameters - a source string and a constant indicating the type of the filter. In addition to validating email addresses (FILTER_VALIDATE_EMAIL), this function supports the following constants: FILTER_VALIDATE_URL - checks the value for the correctness of the URL (for example), FILTER_VALIDATE_IP - checks the value for the correctness of IP addresses, FILTER_VALIDATE_REGEXP - checks the value for the correctness of the regular expression syntax and several other constants, which are alternatives to the functions is_bool(), is_float(), is_int(), etc.

This and the following sections will briefly cover how to create basic web applications using PHP. What was discussed in the section is clearly not enough for your application to communicate with the user and formulate depending on the actions he performed or the parameters he entered. What's missing? There is not enough knowledge on how to organize user data input and transfer of this data to the server. Well, you should already have basic knowledge about 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. Contacting 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 saved as bookmarks. 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 present on the command line. The number and size of parameters is unlimited.

    It is believed that the results of multiple identical POST requests may return different values ​​because 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 parameters when there is no need to make changes to the data structures of the target resource, and it makes sense to save the request (URL) in bookmarks. The GET method may be faster than similar requests using the POST method.

The POST method should be used when you need to hide 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 a description of these changes in the parameters (in the body of the request).

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

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

Http://site/php-samples/sql.php?sql=select * from d_staff

To access request parameters on the server side, you should use global arrays $_GET And $_POST respectively. If your application doesn't care which method it is accessed by, 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 yes, it assigns its value to the corresponding variable, and if not, it assigns it an empty value.

Defining HTTP request parameters via HTML form

Of course, defining parameters manually directly in the browser command line is not very convenient. This method is suitable for programmatically executing HTTP requests when web applications communicate with each other. In order to enter and carry out initial data verification on the client side, you should use HTML forms and . Below is an example of the simplest form using 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 the method of transmitting data to the server (get or post). The action attribute specifies php file, which 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 must be passed as an HTTP request parameter, you must define a unique value for the name attribute. It is the attribute value name will be index in the $_GET, $_POST or $_REQUEST arrays (see example above). Pressing a button submit sends the form with all entered values ​​to the server.