Contacts

Get and post examples. Attribute Action and Method. GET and POST methods. Choice between Get and Post

Modern web resources do not just provide information to the visitor, but also interact with it. To interact with the user, you need to receive some information from it. There are several methods for obtaining data, very common methods. Get. and POST.. And respectively B. Php. There is support for these data transfer methods Get. and POST.. Let's see how these methods work.
GET MethodData gET. Transmitted by adding them to the URL address of the called scenario intended for processing received information. To explain this method, dial the resource URL in the address bar in the address bar and add the question mark first (?), And then the number num \u003d 10. for example

http: //domure.ru/script.php? num \u003d 10


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

http: //localhost/script.php? num \u003d 10


In this case, we transmit the NUM parameter to 10. To add the following parameters, the script must be used - ampersant (&), for example

http: //domure.ru/script.php? Num \u003d 10 & Type \u003d New & V \u003d Text


In this case, we transferred three parameters to the script: Num with a value of 10, Type with the "New" and V value with the "Text" value.
To get these parameters in the script you need to use a built-in array. $ _Get. $ _Get ["num"], $ _get ["type"], $ _ get ["V"]. These array elements will contain the values \u200b\u200bof the transmitted parameters. To demonstrate this example, create a Script.php file as follows.



Checking the GET method in PHP


echo ($ _Get ["Num"]. "
");
echo ($ _Get ["Type"]. "
");
echo ($ _GET ["V"]);
?>




And now call this file in the browser

http: //at/script.php? Num \u003d 10 & Type \u003d New & V \u003d Text


and you will see the transmitted parameters in the browser window. But if you call this file without additional parameters http: ////script.php, you will see errors that will issue an interpreter Php.That there is no such elements of the array $ _Get. Checking these data from the user can be highlighted not one article, so in this article I will not touch this moment.
As you probably understand, to force the user to dial data in the address bar is not very good and completely inconvenient. Therefore, to receive data from the user you need to use HTML-form. Write a simple HTML -form.


Enter the number

Do you have a computer?

Your comment:





I comment on the created form. Forms are created by the Form tag. The form fields are created by INPUT, SELECT, TextAREA tags (you can read more). In the Form tag, the URL of the script is specified in the Action attribute, which will receive these forms. In our case, we have already specified the already existing Script.php file. The Method attribute sets the data sending method. We indicated the method Get.. Now we know what file these file will be transmitted, and which way, it remains to figure out where to look for them?!
This form data will be transferred to the web resource browser by adding them to the URL: will first be a question mark (?), Then the parameters are separated by ampersant (&). The parameter name will be taken from the Name attribute, which must be spelled out from any field field. The value of the parameter will depend on the type of field. If the field is textual, the text entered by the user will be the user. If the field will be a list, a group of switches or flags, then the value of the value of the value of the selected item will be the value of the parameter. I will explain on the example of our form. If the user enters the number 10 in the INPUT field, then the name of the parameter will be Num (the value of the Name attribute of the INPUT tag), and the value will be the value (user-entered number). Accordingly, the browser will form a pair of "num \u003d 10". If the user from the list selects the option "Yes", then the name of the parameter will be Type (the value attribute of the Name Tag SELECT), and the value will be the value (value of the value of the value Tag Option). Accordingly, the browser will form a pair of "Type \u003d YES".
Now this form will be placed on the forma.php page.



Data transfer form using GET and PHP



Enter the number

Do you have a computer?

Your comment:









Enter any values \u200b\u200bin the form fields and click the "Submit" button. After pressing the browser button, opens another page (script.php), and the data you entered the browser window will be displayed. I think it is clear why: the browser will transfer data to the script script.php, and in the script, these data will be processed and displayed.
POST methodNow let's look at how the method works POST..
To send these methods POST. You need to use HTML-form. How do we remember that the method of the form is responsible for the method of sending the form data form. Therefore, you need to specify the POST value in the Method attribute. Otherwise, the form may be the same as for the GET method. We will change our shape that we have already used to transfer data to the GET method for transmitting by the POST method.


Enter the number

Do you have a computer?

Your comment:





As you can see, the form remains the same with the exception of the attributes of Method and Action. Now the data will be passed to the script_post.php script. Position our form on the forma_post.php page.



POST and PHP data transfer form



Enter the number

Do you have a computer?

Your comment:









Now you need to write a script that will process our form data.
To obtain a transmitted method in the data script POST. need to use a built-in array $ _Post.. The keys of this array will be the names of the parameters. In our case, you need to use $ _Post ["num"], $ _post ["type"], $ _ post ["V"]. These array elements will contain the values \u200b\u200bof the transmitted data. As you see the difference from using the GET method, it is only expressed only in the use of an array $ _post. Therefore, we will not be difficult to write a script_post.php file:



Verification of the POST method in PHP


echo ($ _POST ["NUM"]. "
");
echo ($ _Post ["Type"]. "
");
echo ($ _post ["v"]);
?>




Now open the forma_post.php file in the browser. Enter some data in the form field and press the "Submit" button. Now, probably, you noticed the difference between the POST method from GET - these forms did not appear in the address bar of the browser. Data method POST. You can not pass through the address bar of the browser. This essential difference needs to be remembered.
IN Php. In independence, what method data was sent - by the POST method or the GET method - to obtain data using an $ _request array. Comparison of GET and POST methodsWhen using the GET method, data is transmitted by adding to the URL. Thus, they will be visible to the user that in terms of safety is not always good. Also, the maximum amount of transmitted data will depend on the browser - from the maximum permissible number of the characters of the browser address bar.
When using the POST method, the data will not be visible to the user (not displayed in the address bar of the browser). And therefore, they are more protected, and, therefore, the program processing this data is more protected in terms of safety. Also, the amount of transmitted data is practically not limited.
When choosing a way of data transfer, you need to consider the features given and stop at the most acceptable method.

In common between them, the fact that they work equally. The difference between them is technically no. But there is ideological differences.

I will tell about them in the context of PHP. Please note that the HTTP protocol to PHP has an indirect attitude because it was created to exchange HTML pages and PHP simply expands the possibilities and the other.

Get a query is used to get data A POST to send. (I remind you that technically work equally).

Therefore, in the context of PHP, relying on this ideology was made as follows:
1. Each time PHP is launched, superglobal arrays ($ _Get, $ _Post) are created by default.
2. If there is a question mark in the query string (?). Then everything is considered after it parameters GET requests they are presented in the "key" format \u003d "value" and an ampersand sign (&) is used as a separator
Example:
Get /index.php?name\u003dandrey&surname\u003dHalkin
This is a query string, here 2 parameters. These parameters will fall into the $ _get array.
3. $ _Post is filled with another way. The contents of this array are filled from the "request headers". That is, from the place hidden from the eyes explicitly. The whole routine to create such headlines takes on a browser. Although sometimes something is edited in headlines into manual.

Most often, the post request is used in forms (to send data).

For example, we have a form to log in 2 fields login and password.

Imagine that we use the GET method. Then, when sending a form, we turn to the following address /Login.php?Login\u003dandrey&password\u003d123 Agree that this is not safe to transmit such information. Anyone can open your browser and starting to enter the site address. It can see your passwords and login.

But if we specified by the POST method, then we would get the following request:
POST /LOGIN.php (login \u003d Andrey & Password \u003d 123) Whats in brackets would be hidden and not saved in the browser.

In general, summarizing:
Get is to get a certain page in a specific form (sorting, the current page in the blog, the search string, etc.).
POST - for mandrel data that does not affect the page display, in the way that these data only affect the result of the script execution (logins, passwords, credit card numbers, messages, etc.).

And one more good news can be combined, for example
POST /INDEX.php?page\u003dlogin (login \u003d Andrey & Password \u003d 123) I think I have already explained enough that it turns out and what parameters to which array will fall.

GET and POST methods in HTTP and HTTPS are the two most popular methods used to transfer data from the client to the server using the HTTP protocol (hypertext transmission protocol). And the GET and POST can be used to send a request and receive an answer, but there is a significant difference between them.

The difference between Get and Post requests in HTTP or HTTPS is a popular question on each web programming interview. Since HTML does not depend on the web server technology, such as Java, ASP or PHP and HTTP is the main protocol in the Internet space, it is impossible to clearly ignore the importance of understanding the GET and POST methods. In this article, we will look at what the GET HTTP method is, what is the POST HTTP method, when to use one or another request and what is the difference between them. We will analyze every concept separately.

What is HTML?

HTML is a language used to create web pages. Hypertext refers to hyperlinks that can contain an HTML page. Marking language means how to use tags to determine the layout of the page and items on the page.
Below is an HTML example, which is used to determine the basic web page with the heading and one paragraph of the text:



<Голова>
<Название> TechTerms.com.

<Тело>

This is an example of paragraph in HTML.

The first string determines the type of content contained in the document., and which are all included as an example above. Page header, metadata and links to binding files are placed between the actual page contents are between the tags. .

Over the past few decades, the network has survived many changes, but HTML has always been the main language used to develop web pages. Interestingly, although websites have become more advanced and interactive, HTML has become easier. If you compare the HTML5 Page Source with a similar page written in HTML 4.01 or XHTML 1.0, on the HTML5 page there will be less code. This is due to the fact that modern HTML relies on cascading style sheets or JavaScript to format almost all elements inside the page.

Many dynamic websites generate web pages "on the fly" using the Script Server Language, such as PHP or ASP. However, even dynamic pages must be formatted using HTML. Therefore, scenario languages \u200b\u200boften generate an HTML code that is sent to the web browser.

The HTTP hypertext transmission protocol is designed to interact between clients and servers and works as a query-response protocol.

The web browser can be a client, and the application on the computer on which the website is posted, the server.

The client (browser) sends an HTTP request to the server, the server returns a response that contains information about the status of the query and may also contain the requested content.

Two methods of queries get and post

Two frequently used methods for request-response between the client and the server:

    GET - requests data from the specified resource;

    POST - sends data to be processed to the specified resource.

The transfer of GET and POST literally means getting and post-processing.

Read more about http

HTTP is a protocol used to transfer data via the Internet. It is part of the Internet protocol package and defines commands and services used to transmit web page data.

HTTP uses the Server-Client model. The client can be a home computer, a laptop or a mobile device. The HTTP server is usually a web host with a web server software, such as Apache or IIS. When the user gets access to the website, the browser sends a request to the appropriate web server and meets the HTTP status code. If the URL is valid and the connection is provided, the server will send the web page to the browser and related files.

General HTTP status codes include:

    200 - a successful request (there is a web page);

    301 - moves constantly (often redirected to a new URL);

    401 - unauthorized request (authorization required);

    500 - Internal server error (frequently caused by incorrect server configuration).

POST and GET in http

HTTP defines the GET and POST commands that are used to process form views on websites. The Connect command is used to facilitate a secure connection that is encrypted using SSL. Encrypted HTTP connections occur via HTTPs - HTTP extension intended for secure data transfers.

URLs starting with "http: //" are available according to the standard hypertext transmission protocols and by default use port 80. URLs starting with "https: //" are available through a secure HTTPS connection and often use port 443.

POST.

POST is a series of system checks performed by computers and other electronic devices when they are turned on. The test results can be displayed on the screen, output through flashing LEDs or simply recorded inside. In computer systems, the POST operation is performed at the beginning of the boot sequence. If all tests are passed, the rest of the start process will be continued automatically.

Operating systems Mac and Windows devices start POST each time the computer is loaded or restarted. Scanning checks hardware and ensures that the processor, RAM and storage devices will work correctly. If an error occurred during the post, the startup process may pause or completely stop, and the monitor may appear on the PC PC error PCs are often displayed on the BIOS information screen. They can be displayed as cryptic codes, such as "08", or as a system message, such as "system memory error when displaced." On Mac, POST errors are often indicated by simple graphics, for example, a broken folder icon, which indicates that the boot unit is not found.

Physical manifestations

In some cases, the computer screen may not even turn on before the POST errors. If this happens, error codes can be displayed through flashing LED indicators or audio signals. For example, Apple IMAC will play three consecutive tones, to withstand a pause of five seconds, and then repeat the tones when a bad RAM is detected during startup. Most PCs also publish sound signals when POST errors are detected, although each manufacturer uses its own codes.

POST is a pretty technical term that use only computer techniques on a regular basis. However, this is a good abbreviation, because it helps better understand error messages that may appear on computers or other electronic devices. If the computer does not start due to the POST error, you can use another device for finding the value and cause errors from the manufacturer's website. Then you can take the appropriate actions - removing the memory module or re-installing the video card with the subsequent restart equipment.

Get.

POST is also a method for transmitting the HTML form variables from one web page to another, without displaying them in the address bar. Alternative method - GET, which adds values \u200b\u200bto the URL. HTTP POST requests provide additional data from the client (browser) to the server in the message body. On the contrary, Get Requests include all the necessary data in the URL. Forms in HTML can use any method, specifying the method \u003d post or Method \u003d GET (default) in the element

. The specified method determines how these forms are transmitted to the server. When the GET method is used, all form data are encoded in the URL as a query string parameters. With POST, these forms appear in the HTTP query message.

Differences in form representation

The POST query method requests a web server to receive and storing data enclosed in the query message body. It is often used when downloading a file or when sending a completed web form.

The HTTP GET query method retrieves information from the server. As part of the Get query, some data can be transmitted in the URL query line, specifying the search conditions, date ranges, or other information that defines the query.

Within the POST query, an arbitrary amount of data of any type can be sent to the server in the query message body. The header field in the post request typically indicates the type of Internet media message.

The main difference between the Get and Post requests is that they correspond to various HTTP requests as defined in HTTP specifications. The process of feeding both methods begins in the same way: the form data set is created by the browser and is then encoded by the method specified by the EncType attribute. For Method \u003d "POST, the Encype attribute can be MultiPart / Form-Data or Application / X-WWW-FORM-URLENCODED, whereas for Method \u003d" Get "starts only through the Application / X-WWW-FORM-URLENCODED. These form data set Then is transmitted to the server.

To send a form using Method \u003d "Get" a browser creates a URL, taking the value of an action attribute and adding a form data set encoded using the Application / X-WWW-FORM-URLENCODED content type. The browser then processes this URL, as if he referred to the link (or, as if the user had scored the URL manually). The browser divides the URL on the part and recognizes the host, then sends the Get request to this host with the rest of the URL as an argument. It is important to note that this process means that these forms are limited to ASCII codes. Special attention should be paid to coding and decoding other types of characters when transmitting them to the URL in ASCII format.

Presentation of the form with Method \u003d "POST" causes sending a POST request using an action attribute value and a message created in accordance with the content type specified by the Encype attribute.

Php.

PHP is a built-in HTML. This means that the PHP code can be inserted into the HTML page. PHP code is read or analyzed by the server on which the page is located. The output of the GET and POST functions in PHP on the page is usually returned as an HTML code that can be read by the browser. Since the PHP code is converted to HTML before downloading the page, users cannot view the PHP code on the page. This makes PHP pages sufficient to access databases and other protected information.

Most of the PHP syntax is borrowed from other languages, such as C, Java and Perl. However, PHP has a number of unique features and special features. The purpose of this language is to enable web developers to quickly and easily write dynamically generated pages.

WordPress.

WordPress is a free content management system used to create and maintain websites. Its simplicity of use and unique blogging functions helped him become the most popular blog management tool on the Internet.

The Wordpress interface allows anyone who has no web development experience, create and publish a website. Built-in blogging tools provide an easy way to track individual messages, visitors and user comments.

Despite the fact that thousands of Wordpress and plug-ins templates are available, the Post Get GET system in Wordpress still has its limitations. Since this is a template-based service, the user must start with a predetermined website, and not to create pages from scratch. In addition, it is not possible to insert scripts or maintain a database with the same level of control that the user's website offers.

POST_GET_ID () tool allows you to use scripts to control the element, as it has a unique identifier, and when sending it in the form of a form through these methods, the drop-down list will be shipped with a unique identifier that allows the script to notice which publication works. As an alternative, a hidden variable can be sent, which will allow the script to see which publication refers to the presentation.

This post is the answer to the question set in the comments to one of my articles.

In the article, I want to tell what the HTTP methods are GET / POST / PUT / DELETE and others, for which they were invented and how to use them in accordance with the REST.

Http.

So, what is one of the main Internet protocols? Pedants send to RFC2616, and the rest will tell about humanly :)

This protocol describes the interaction between the two computers (client and server), built on the database of messages, called the Request) and response (Response). Each message consists of three parts: starting line, headlines and body. In this case, only the starting line is mandatory.

The starting lines for the request and response have a different format - we are only interested in the starting line of the query, which looks like this:

Method URI Http / Version. ,

Where Method is just the HTTP query method, the URI is the resource identifier, version is the version of the protocol (currently updated version 1.1).

Headers are a set of pair name, separated by colon. In the headers, various service information is transmitted: the message encoding, the name and version of the browser, the address from which the client came (Referrer) and so on.

The message body is, in fact, the data transmitted. In response transmitted data, as a rule, the HTML page that the browser requested, and in the query, for example, in the message body, the contents of files downloaded to the server are transmitted. But as a rule, the message body in the query is generally absent.

An example of http interaction

Consider an example.

Inquiry:
Get /index.php HTTP / 1.1 Host: Example.com User-Agent: Mozilla / 5.0 (X11; U; Linux i686; RU; RV: 1.9B5) GECKO / 2008050509 Firefox / 3.0b5 Accept: Text / Html Connection: Close
The first line is the query string, the rest are headlines; There is no body message

Answer:
HTTP / 1.0 200 OK Server: NGINX / 0.6.31 Content-Language: RU Content-Type: text / html; Charset \u003d UTF-8 Content-Length: 1234 Connection: Close ... HTML Page ...

Resources and methods

Let's go back to the starting line of the request and remember that it presents such a parameter as URI. This is decrypted as UNIFORM Resource Identifier - a uniform resource identifier. The resource is, as a rule, the file on the server (example of the URI in this case "/STYLES.CSS"), but at all, there may be any abstract object ("/ blogs / WebDev /" - indicates the block "Web Development ", not on a specific file).

The HTTP query type (also called the HTTP method) indicates the server to the fact that we want to produce with a resource. Initially (in the early 90s) it was assumed that the client could only want one to get it from the resource - to get it, but now, by the HTTP protocol, you can create posts, edit profile, delete messages and much more. And these actions are difficult to combine the term "receipt".

To delimit action with resources at the HTTP method level and the following options were invented:

  • Get - Getting a Resource
  • POST - resource creation
  • PUT - resource update
  • Delete - Delete Resource
Pay attention to the fact that the HTTP specification does not oblige the server to understand all methods (which is actually much more than 4) - only the GET is required, and also does not indicate the server that it should do when receiving a request with one or another method. And this means that the server in response to the delete /index.php request http / 1.1 is not obliged to Delete index.php page on the server, as well as to get /index.php HTTP / 1.1 request is not obliged to Return the index.php page to you, it can delete it, for example :)

REST enters the game

REST (REPRESENTATIONAL STATE TRANSFER) is the term was introduced in 2000 by ROEM Fielding (Roy Fielding) - one of the developers of the HTTP protocol - as the name of the group of website construction principles. In general, the REST covers a wider area than http - it can be applied in other networks with other protocols. REST describes the principles of client's interaction and server, based on the concepts of "resource" and "verb" (you can understand them as subject to both). In the case of HTTP, the resource is determined by its URI, and the verb is an HTTP method.

REST proposes to refuse to use the same URI for different resources (that is, the addresses of two different articles like /Index.php?article_id\u003d10 and /index.php?article_id\u003d20 is not the REST-WAY) and use different HTTP methods for different actions. That is, a web application written using the REST approach will delete a resource when accessing it with the HTTP method of Delete (of course, this does not mean that it is necessary to give the opportunity to remove everything and everything, but any A request for deletion in the application must use the HTTP-Delete method).

REST gives programmers the ability to write standardized and slightly more beautiful web applications than before. Using the REST, URI to add a new user will not be no /user.php?Action\u003dCreate (GET / POST method), and simply /User.php (Strict POST method).

As a result, together the existing Specification HTTP and the REST approach finally acquire the meaning of various HTTP methods. Get - Returns the resource, POST - creates a new, PUT - updates the existing, delete - deletes.

Problems?

Yes, there is a small problem with the use of the REST in practice. This problem is called HTML.

PUT / DELETE Requests can be sent via XmlHttpRequest, by referring to the Manual Server (say, via CURL or even via Telnet), but you cannot make an HTML form that sends a full-fledged PUT / DELETE request.

The fact is, the HTML specification does not allow you to create forms sending data differently than via GET or POST. Therefore, for normal operation with other methods, they have to imitate them artificially. For example, in Rack (a mechanism on the basis of which Ruby interacts with the web server; with Rack, RAILS, MERB and other Ruby frameworks are made) in the form you can add a hidden field called "_Method", and as a value specify the name of the method (For example, "PUT") - In this case, a post-request will be sent, but Rack will be able to pretend that I got PUT, and not POST.

HTML form. Arrays $ _post and $ _get

HTML form. Methods for sending data to the server

With HTML-forms you probably have already met:

Enter your name:

Saving this code in the HTML file and viewing it with your favorite browser, you will see the usual HTML form:

Tag

having a pair final tag
, Actually, asks the form. His attributes are both optional:

  • action - Indicates the URL (full or relative) to which the form will be sent. If this attribute does not specify, most browsers (more precisely speaking, all browsers known to me) send a form to the current document, that is, "on themselves". This is a convenient reduction, but according to the HTML standard, the Action attribute is required.
  • method is a way to send form. There are two of them.
    • Get - sending form data in the address bar.
      Could you notice the presence at the end of the URL of the Symbol "?" And the following data in the format parameter \u003d value. Here "Parameter" corresponds to the value of the Name attribute of the form elements (see below about TEG ), and the "value" - the contents of the Value attribute (in it, for example, contains the user input into the text field of the same tag ).
      For example, try searching for something in Yandex and pay attention to the address bar of the browser. This is a GET method.
    • POST - Mold These are sent in the query body. If it is not entirely clear (or it is completely unclear), what it is - do not worry, we will soon be back to this issue.
    If the Method attribute is not specified - the GET is meant.

Tag - Specifies the form element defined by the Type attribute:

  • The "Text" value sets a single-line input field
  • The value "submit" sets the button, when the form is pressed to the server

Other values \u200b\u200bare possible (and - not the only tag that is specifying the form element).

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

  1. The browser browsing the elements included in the shape and generates from their Name and Value attributes these forms. Suppose the name Vasya has been introduced. In this case, these forms - Name \u003d Vasya & Okbutton \u003d OK
  2. The browser establishes a connection to the server, sends a request to the server specified in the Action Tag Attribute
    Using the sending method specified in the Method attribute (in this case - Get), transmitting data in the query.
  3. The server analyzes the received query, forms an answer, sends it to the browser and closes the connection
  4. The browser displays the document received from the server.

Sending the same query manually (with telnet help) looks like this (suppose the domain name of the site is www.example.com):

Telnet www.example.com 80 get /cgi-bin/form_handler.cgi?name\u003dvasya&okbutton\u003dok http / 1.0 \\ r \\ n host: www.example.com \\ r \\ n \\ r \\ n

As you, most likely, have already guessed, pressing the submit button in the form with the method of sending "Get" is similar to the input of the corresponding URL (with a question mark and form data at the end) in the browser address bar:

Http://www.example.com/cgi-bin/form_handler.cgi?name\u003dvasya&okbutton\u003dok

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

Perhaps all these technical details and exercises with the Telnet-Ohm seem incredibly boring and even unnecessary ("and what have PHP?"). And in vain. :) These are the basics of work on the HTTP protocol, which you need to know to each Web programmer, and this is not theoretical knowledge - all this is useful in practice.

Now replace the first string of our form to the following:

We pointed out the send method of "POST". In this case, the data is sent to the server in several other way:

Telnet www.example.com 80 post /cgi-bin/form_handler.cgi http / 1.0 \\ r \\ n host: www.example.com \\ r \\ N Content-Type: Application / X-WWW-FORM-URLENCODED \\ R \\ When using the POST method, these forms are sent after "two ENTERS" - in the query body. All that above is actually a query header (and when we used the GET method, these forms were sent in the title). In order for the server to know how to finish reading the bodies of the request, the title is present in the Content-Length line; About the same that the form data will be transmitted by parameter1 \u003d value1 & parameter2 \u003d value2 ..., and the values \u200b\u200bare transmitted as Urlencode - that is, just as with the GET method, but in the query body, the server reports the Content header -Type: Application / X-WWW-FORM-URLENCODED.

The advantage of the POST method is the lack of limit on the length of the string with the form data.

When using the POST method, it is impossible to send a form, just "going on the link", as it was with Get.

When using POST-form, in its Action attribute you can specify after the question mark and parameters get-form. Thus, the POST method includes both the GET method.

Arrays $ _Get and $ _POST

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

{!LANG-541c2913aadf0ce111d1ff1913fd08c2!}

Consider a simple example:



if ($ _Server ["Request_Method"] \u003d\u003d "POST") (
Echo "

Hello, "$ _Post [" Name "]."

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






The form in lines 8-12 contains two items: name and okbutton. The Method attribute specifies the POST form method, the Action attribute indicating the URL to which the form is sent is filled with the PHP_SELF server variable value - the address of the script at the moment.

- Abbreviated form of recording for .

Suppose, in the Name field, we entered the value of Vasya, and the OK button was pressed. At the same time, the browser sends to the POST server. Query Body: Name \u003d Vasya & Okbutton \u003d OK. PHP automatically fills the $ _POST array:

$ _Post ["Name"] \u003d "Vasya"
$ _Post [okbutton] \u003d "OK"

In fact, the value of "Vasya" is sent to the browser in the Urlencode-form; For Windows-1251 encoding, this value looks like% c2% E0% F1% FF. But, since PHP automatically performs the necessary decoding, we can "forget" about this feature - until you have to work with HTTP queries manually.

Since in the query body, only names and values \u200b\u200bare indicated, but not the types of form elements, PHP has no idea, corresponds to $ _post ["name"] input row, button, or list. But this information, in general, is absolutely not needed. :)

Since you know what is written on the Submit button, we are optional, in line 11 you can delete the Name attribute, shorting the button description to . In this case, the browser will send the Name \u003d Vasya-Vasya.

And now - the same, but for get-shaped:



if (ISset ($ _ get ["Name"])) (
Echo "

Hello, "$ _Get [" Name "]."

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







In line 8 it would be possible to write with the same success

: Get - the default method. This time, the browser sends the GET-request, which is equivalent to entering the address bar of the address: http: //adress-site./mety-script.php? Name \u003d Vasya.

PHP with GET-Forms enters the same way as with POST, with the difference that the $ _GET array is filled.

The cardinal difference is in the line 4. Since the simple input of the address in the browser string is a Get-queuity, check if ($ _Server ["Request_method"] \u003d\u003d "Get") is meaningless. Therefore, we resort to the ISSET () design, which returns True if this variable is defined (i.e., it was assigned a value), and false - if the variable is not defined. If the form has been filled - as you already understood, PHP automatically assigns $ _get ["Name"] the corresponding value.

The inspection is used using ISSET () - universal, it could be used for post-form. Moreover, it is preferable, as it allows you to find out which fields of the form are filled.

A little more complex example.




Echo "Specify the name!
" ;
< 1900 || $_POST [ "year" ] > 2004 ) {
Echo.
"
;
) ELSE (

" ;

Echo "You. $ Age. " years
" ;
}
Echo "


" ;
}
?>
">
Enter your name:


Enter your year of birth:







No new techniques are not used here. Observe, execute the code, try modifying ...

Change the last example so that the user does not need to re-fill the fields. To do this, fill the Value attributes of the form elements just entered values.



$ Name \u003d Isset ($ _ post ["Name"])? $ _Post ["Name"]: "";
$ year \u003d isset ($ _ post ["year"])? $ _POST ["YEAR"]: "";

If (ISset ($ _ POST ["NAME"], $ _post ["year"])) (
if ($ _post ["name"] \u003d\u003d "") (
Echo "Specify the name!
" ;
) ELSE if ($ _post ["year"]< 1900 || $_POST [ "year" ] > 2004 ) {
Echo. "Specify the year of birth! Valid range of values: 1900..2004
"
;
) ELSE (
Echo "Hello,". $ _Post ["Name"]. "!
" ;
$ age \u003d 2004 - $ _post ["year"];
Echo "You. $ Age. " years
" ;
}
Echo "


" ;
}
?>
">
Enter your name:


Enter your year of birth:







A few incomprehensible lines 4 and 5. Everything is very simple: the line 4 could be recorded like this:

if (isset ($ _ post ["Name"]))
$ name \u003d $ _post ["Name"];
eLSE.
$ Name \u003d "";

A question may arise - why not throw away the strings 4-5 and not write:

Enter your name: ">

Enter your year of birth: ">

The fact is that if these posts are not defined - and it will be, if the form has not yet been filled, - PHP will issue warnings about the use of uninitialized variables (and, well-founded: Such a message allows you to quickly find hard-fastened typos in variable names, And also warns of possible "holes" on the site). You can, of course, put the code with ISSET directly into the form, but it turns out too cumbersome.

Figured out? And now try to find an error in the code below. Well, not quite a mistake, but defects.

hTMLSPECIALCHARS ()

Didn't find? I will tell you. Enter, for example, in the "Name" field double quotes and some text, for example, VA "Sia. Send a form, and take a look at the source code of the page received. In the fourth line there will be something like:

Enter your name:

That is - nothing good. And if the cunning user entered the JavaScript code?

To solve this problem, it is necessary to use the HTMLSpecialChars () function, which will replace the service characters on their HTML representation (for example, quotes - on "):



$ Name \u003d Isset ($ _ post ["Name"])? HTMLSPECIALCHARS ($ _POST ["NAME"]): "";
$ year \u003d isset ($ _ post ["year"])? HTMLSPECIALCHARS ($ _POST ["YEAR"]): "";

If (ISset ($ _ POST ["NAME"], $ _post ["year"])) (
if ($ _post ["name"] \u003d\u003d "") (
Echo "Specify the name!
" ;
) ELSE if ($ _post ["year"]< 1900 || $_POST [ "year" ] > 2004 ) {
Echo. "Specify the year of birth! Valid range of values: 1900..2004
"
;
) ELSE (
Echo "Hello,". $ Name. "!
" ;
$ age \u003d 2004 - $ _post ["year"];
Echo "You. $ Age. " years
" ;
}
Echo "


" ;
}
?>
">
Enter your name:


Enter your year of birth:







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

Remember - the HTMLSpecialChars () function must always be used when the contents of the variable in which the HTML special might be present is displayed.

phpinfo ()

The phpinfo () function is one of the most important in PHP. It displays information about PHP settings, the values \u200b\u200bof all kinds of configuration variables ...

Why do I mention her in the article on the forms? phpInfo () - more comfortable debugging tool. phpinfo (), among other things, displays the values \u200b\u200bof all $ _Get, $ _post and $ _server variables. So, if the variable forms "lost", the easiest way to detect, what is the case - use the phpinfo () function. In order for the function to display only the values \u200b\u200bof the variables (and you did not have to scroll through a tens of pages), it should be called as follows: phpinfo (info_variables); , or - that is absolutely the same - phpinfo (32);.



">
Enter your name:


phpinfo (32);
?>



Or, for example, this situation: you want to know the visitor's IP address. You remember that the corresponding variable is stored in an array of $ _Server, but - that's not enough - they forgotten exactly how the variable is called. Again, call phpinfo (32); , We are looking for your IP address in the plate and find it - in the $ _Server string ["Remote_addr"].



Did you like the article? Share it