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.
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.
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.
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.
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.
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:
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. название>
HEAD>
<Тело>
This is an example of paragraph in HTML. p>
Body>
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
Saving this code in the HTML file and viewing it with your favorite browser, you will see the usual HTML form:
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.
- Get - sending form data in the address bar.
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?
- 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
- The browser establishes a connection to the server, sends a request to the server specified in the Action Tag Attribute
- The server analyzes the received query, forms an answer, sends it to the browser and closes the connection
- 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 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.
=$_SERVER["PHP_SELF"]?> - Abbreviated form of recording for echo $_SERVER["PHP_SELF"]; ?> .
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 "]."
!" ;}
?>
In line 8 it would be possible to write with the same success
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 "
" ;
}
?>
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 "
" ;
}
?>
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);.
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"].