Difference between post get requests. GET or POST: what to choose? Passing Variables Using the GET Method

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 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

Nowadays, only two HTTP methods are most often used: GET and POST. But it turned out that even among these two “pine trees” web developers manage to get lost. There is an explanation for this: both methods can be used to obtain the same result. But we must remember that the thoughtless use of any of the methods can lead to disastrous consequences, including heavy loads on the channel and security holes.

To avoid this, it is enough to simply understand in more detail the purposes and differences of these methods.

If you delve into the meaning of method names, a lot will become clearer. GET (from English to receive), i.e. should be used to query data. POST (from English send by mail) - used to send data to the server. Everything seems to be extremely simple and clear. But whoever wants to develop websites a little more complicated than a business card website with one feedback form, it’s better to get to know the issue better.

Secure and insecure HTTP requests

The HTTP 1.1 specification introduces two concepts: secure and insecure request, or more precisely, method.

Safe methods are methods that can only request information. They cannot change the requested resource, nor can they lead to undesirable results for the user, others, or the server. Examples of safe ones are requesting the HTML code of a web page or image. Safe methods include HEAD and GET.

The note

In reality, craftsmen, of course, can cause harm with GET requests. For example, query loops.

Unsafe queries, as everyone has already guessed, can potentially lead to bad consequences if they are used again. Such requests may change the content of the resource being accessed. Examples of such requests: sending messages, registration, online payments. Unsafe methods include POST, PUT, DELETE.

Idempotent methods

Idempotency is a property of methods that, with numerous repeated calls, will return the same result, except in cases where the information is out of date. This means that when accessing the same URL, all users will see the same web page, image, video, etc. The GET, PUT, DELETE methods have this property.

Now let’s take a closer look at the GET and POST methods themselves: let’s write a short “summary” for each.

GET

  • designed to receive data from the server;
  • the request body is empty;
  • processed on the server side faster and with less consumption of server resources due to the empty request body;
  • the transfer of variables occurs in the address bar (this is how the user sees it; technically, the data is transmitted in the query line) and therefore information about the variables and their values ​​is visible (the data is not protected);
  • is able to transfer a small amount of data to the server: there are restrictions on the length of the URL, which depends on the browser, for example, IE6 = 2Kb. Yahoo! developers recommend focusing on this number;
  • can only transmit ASCII characters;
  • such a request can be copied and saved (for example, in bookmarks);
  • the request can be cached (this can be controlled);
  • to further reduce the load on the channel and server, conditional and partial requests are available;
  • does not break the HTTP connection (if keepAlive mode is enabled on the server).

POST

  • intended for sending data to the server;
  • data transfer occurs in the body of the request;
  • server-side processing is slower and “heavier” than GET, because in addition to headers, the request body must be analyzed;
  • capable of transmitting large amounts of data;
  • capable of transferring files;
  • a page generated by the POST method cannot be saved as bookmarks;
  • breaks the HTTP connection;
  • To transmit even a very small amount of information, most browsers send at least two TCP packets: a header and then a body of the request.

It turns out that these two methods are not so similar. The use of one or another should be determined by the task at hand, and not by the fact that GET is used by default or is easier to work with. GET, of course, is a better option in most cases, especially when building fast AJAX, but do not forget about its disadvantages. For myself, I made a simple algorithm-note on choosing a method.

You may have noticed that on most sites you can see the following addresses:

Http://site/index.php?blog=2

Here, even without knowing php, you can guess that we are accessing a file index.php But few people know what comes after the question mark. It's quite simple: ?blog=2 This is a declaration of the global variable "$_GET["blog"]" with the value "2". Thus, I pass a variable into the script that is responsible for displaying information from the database. Let's write a small script in which you can clearly see everything:

if(isset($_GET["blog"])) (
echo $_GET["blog"];
}
?>

We use the if() condition operator and the following line is used as a condition:

Isset($_GET["blog"])

isset() allows you to find out whether the variable specified in brackets exists, that is, the condition that I described in the code sounds like this: If the variable $_GET["blog"] exists, then display the contents of this variable on the screen. Here's what happened:

I think it’s clear A global variable is created $_GET with the identifier that we declared in the address bar ( in this case with the identifier “blog”)

Now I want to clarify one point. Suppose we need to declare two variables, how to do this? The first variable is declared after the question mark "?" The second variable is declared after the “&” sign ( To be honest, I don’t know what this sign is), here is an example declaration of three variables:

Http://site/index.php?a=1&b=2&c=3

Here is the output code:

if(isset($_GET["a"]) AND isset($_GET["b"]) AND isset($_GET["c"])) (
echo $_GET["a"]."
";
echo $_GET["b"]."
";
echo $_GET["c"]."
";
}
?>

The condition sounds like this:

If there is a global variable $_GET["a"] and a global variable $_GET["b"] and a global variable $_GET["c"] then display them on the screen, here is the result:

Forms

Before we get to post requests, you need to understand what forms are? Why is it necessary? Because the global variable $_POST[""] is created through forms. What is form? These are fields for the user to enter some information. There are one-line fields, large fields, and also radio buttons and check boxes. Let's take everything in order...

The form is a tag:


form elements

The form has attributes, I will list the most common ones:

Let's create a form:


form elements

I set the file as a handler file test.php since it is in it that I write examples for you. I set the sending method to post because these are the methods used in 99.9% of cases. I also gave our form a name - form

Now let's plunge into the world of form elements. The first thing you need to understand is that almost all elements are a tag the only difference is in the attribute type at these tags. Let me list the form elements used:

I’m sure you’ve seen such fields more than once, so here’s what they say: “no comments”

Now let's create a small training questionnaire, which we will work with further. Our task is to create a small questionnaire that will tell us the name of the person filling it out, gender, what country they are from, favorite color and a text field where the user can add something about themselves. Here's what I got:

Your Last Name First Name Patronymic:

What's your gender:
M
AND

What country are you from



Favorite color(s):

Black:
Red:
White:
Another:

About Me:




Note that almost every tag has an attribute value, what is it for? It records the data that you are going to transfer to another page. I hope it's clear

Now if we run this code in the browser, we will see the following:

For the form I used the attribute action with meaning test.php this means, as I already said, that the data from the form will be transferred to the test.php file.

POST request

Now let's write PHP code that will allow us to see the information we entered. Where is the data stored? In the case of the get request, our data was in the global variable $_GET[""]. When making a post request, the data will be stored in the global variable $_POST[""]. IN square brackets, it is necessary to register, as in the case of the global variable get, an identifier. The question is, where can I get this identifier? That's why we need the name attribute on form elements! It is these names that serve as our key in the global post array. Well, let's start describing the script:

if(isset($_POST["submit"])) (
echo "Full name: ".$_POST["fio"]."
";
echo "Gender: ".$_POST["sex"]."
";
echo "Country of residence: ".$_POST["city"]."
";

Echo "Favorite color(s):
";
echo $_POST["color_1"]."
";
echo $_POST["color_2"]."
";
echo $_POST["color_3"]."
";
echo $_POST["color_4"]."
";
echo "About yourself: ".$_POST["about"]."


";
}
?>

The if condition we wrote says: If there is a global variable $_POST["submit"] then we display the data on the screen. This global variable is created if we clicked on the submit button, that's why in in this example the name attribute is required in the button. You may well be wondering why the button's name attribute is optional? It's quite simple. Typically, the programmer does not monitor the button press, but rather monitors the data sent. For correct operation of, for example, a contact form, it is necessary to track not the click of a button, but the correctness of the information entered, and to find out whether this information was entered at all. In our example, we did not check the sent data, but simply tracked the button press, to simplify the example... This is what we got:

Conclusion

Well, today we looked at two methods of transferring data between scripts, and we also got acquainted with forms. I really hope that this information will be useful to you at least somewhere. If you have any questions or thoughts, write comments. Good luck to you, that's all for today!

P.S.: Do you want computer games to become even more realistic? directx 11 for windows 7 can be downloaded for free on windows in! Enjoy wonderful graphics!

GET and POST methods in HTTP and HTTPS are the two most popular methods used to transfer data from client to server using HTTP (HyperText Transfer Protocol). Both GET and POST can be used to send a request and receive a response, but there are significant differences between them.

The difference between GET and POST requests in HTTP or HTTPS is a popular question in every web programming interview. Since HTML is independent of web server technology like Java, ASP or PHP and HTTP is the main protocol in the Internet space, the importance of understanding GET and POST methods cannot be clearly ignored. In this article, we'll look at what the HTTP GET method is, what the HTTP POST method is, when to use each request, and what the difference is between them. Let's look at each concept separately.

What is HTML?

HTML is the language used to create web pages. Hypertext refers to the hyperlinks that an HTML page may contain. Markup language refers to the way tags are used to define the layout of a page and the elements on a page.
Below is an example of HTML that is used to define a basic web page with a title and one paragraph of text:



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

<Тело>

This is an example of a paragraph in HTML.

The first line specifies the type of content contained in the document., And , which are all included in the example above. The page title, metadata and links to anchor files are placed between the actual page content is placed between the tags .

The web has gone through many changes over the past few decades, but HTML has always been the primary language used to develop web pages. Interestingly, while websites have become more advanced and interactive, HTML has become simpler. If you compare the source of an HTML5 page to a similar page written in HTML 4.01 or XHTML 1.0, the HTML5 page will have less code. This is because modern HTML relies on Cascading Style Sheets or JavaScript to format almost all elements within a page.

Many dynamic websites generate web pages on the fly using a server-side scripting language such as PHP or ASP. However, even dynamic pages must be formatted using HTML. Therefore, scripting languages ​​often generate HTML code that is sent to the web browser.

The HTTP Hypertext Transfer Protocol is designed for communication between clients and servers and works as a request-response protocol.

The web browser can be the client, and the application on the computer hosting the website can be 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 request and may also contain the requested content.

Two request methods GET and POST

Two commonly used methods for request-response between client and server are:

    GET - requests data from the specified resource;

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

The translation of GET and POST literally means receiving and post-processing.

More about HTTP

HTTP is a protocol used to transmit data over the Internet. It is part of the Internet Protocol suite and defines the commands and services used to transmit web page data.

HTTP uses a server-client model. The client can be a home computer, laptop or mobile device. An HTTP server is typically a web host with software web server such as Apache or IIS. When a user accesses a website, the browser sends a request to the appropriate web server and responds with an HTTP status code. If the URL is valid and the connection is granted, the server will send the web page and associated files to the browser.

Common HTTP status codes include:

    200 - successful request (web page exists);

    301 - Moves constantly (frequently redirects to a new URL);

    401 — unauthorized request (authorization required);

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

POST and GET in HTTP

HTTP defines the GET and POST commands that are used to process form submissions on websites. The CONNECT command is used to facilitate a secure connection that is encrypted using SSL. Encrypted HTTP connections occur over HTTPS, an extension of HTTP designed for secure data transfers.

URLs starting with "http://" are accessible over standard hypertext transfer protocols and by default use port 80. URLs starting with "https://" are accessible over a secure HTTPS connection and often use port 443.

POST

POST is a series of system tests performed by computers and other electronic devices when they are turned on. Test results can be displayed on the screen, displayed via flashing LEDs, or simply recorded internally. In computer systems, the POST operation is performed at the beginning of the boot sequence. If all tests pass, the rest of the startup process will continue automatically.

Mac and Windows device operating systems run POST every time the computer boots or restarts. Scan checks Hardware and ensures that the processor, RAM and storage devices work correctly. If an error occurs during POST, the startup process may pause or stop completely, and a message may appear on the monitor. On PCs, POST errors often appear on the BIOS information screen. They may be displayed as cryptic codes such as "08" or as system message, for example, "System memory offset error." On the Mac, POST errors are often indicated by a simple graphic, such as a broken folder icon, which indicates that the boot device was not found.

Physical manifestations

In some cases, the computer screen may not even turn on before POST errors. If this happens, error codes may be displayed through flashing LEDs or beeps. For example, an Apple iMac will play three consecutive tones, pause for five seconds, and then repeat the tones when bad RAM is detected during startup. Most PCs also beep when POST errors are detected, although each manufacturer uses their own codes.

POST is a fairly technical term that only computer technicians use on a regular basis. However, it is a good acronym because it helps you better understand error messages that may appear on computers or other electronic devices. If your computer won't start due to a POST error, you can use another device to find the meaning and cause of the error from the manufacturer's website. Then you can take the appropriate action - removing the memory module or reinstalling the video card and then restarting the equipment.

GET

POST is also a variable transfer method HTML forms from one web page to another without displaying them in the address bar. An alternative method is GET, which adds values ​​to the URL. HTTP POST requests provide additional data from the client (browser) to the server in the body of the message. In contrast, GET requests include all the required data in the URL. Forms in HTML can use any method by specifying method=POST or method=GET (default) on the element . The specified method determines how the form data is submitted to the server. When the GET method is used, all form data is encoded into the URL as query string parameters. With POST, the form data appears in the body of the HTTP request message.

Differences in Form Presentation

The POST request method requests the web server to accept and store data enclosed in the body of the request message. Often used when uploading a file or submitting a completed web form.

The HTTP GET request method retrieves information from the server. As part of a GET request, some data may be passed in the URL query string, specifying search terms, date ranges, or other information that specifies the request.

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

The main difference between GET and POST requests is that they correspond to different HTTP requests as defined in the HTTP specifications. The submission process for both methods begins in the same way: the form data set is created by the browser and then encoded in the manner specified by the enctype attribute. For METHOD="POST" the enctype attribute can be multipart/form-data or application/x-www-form-urlencoded, whereas for METHOD="GET" it is only triggered via application/x-www-form-urlencoded. This form data is set then sent to the server.

To submit a form using METHOD="GET", the browser constructs a URL by taking the value of the action attribute and appending it to the form's data set, encoded using the application/x-www-form-urlencoded content type). The browser then treats this URL as if it were referencing a link (or as if the user had manually typed the URL). The browser splits the URL into parts and recognizes the host, then sends a GET request to that 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. Particular attention should be paid to encoding and decoding other types of characters when passing them to an ASCII URL.

Submitting a form with METHOD="POST" causes a POST request to be sent using the action attribute value and a message generated according to the content type specified by the enctype attribute.

PHP

PHP is built into HTML. This means that PHP code can be inserted into an HTML page. The PHP code is read or parsed by the server that hosts the page. The output of GET and POST functions in PHP on a page is usually returned as HTML code that can be read by the browser. Because PHP code is converted to HTML before the page loads, users cannot view the PHP code on the page. It does PHP pages sufficient to access databases and other protected information.

Much of PHP's 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 write dynamically generated pages quickly and easily.

Wordpress

WordPress is a free content management system used to create and maintain websites. Its ease of use and unique blogging features have helped it become the most popular blogging tool on the Internet.

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

Even though there are thousands of WordPress templates and plugins available, the POST GET system in WordPress still has its limitations. Since it is a template-based service, the user must start with a pre-built website rather than creating pages from scratch. Additionally, there is no ability to insert scripts or maintain a database with the same level of control that a custom website offers.

The POST_GET_ID() tool allows scripts to manipulate the item as it has a unique ID and when submitting it as a form through these methods the dropdown will be submitted with a unique ID which allows the script to notice which post is running. Alternatively, a hidden variable could be sent which would allow the script to see which post belongs to the view.

What they have in common is that they work the same way. There is technically no difference between them. But there are ideological differences.

I'll talk about them in the context of PHP. Please note that the HTTP protocol is indirectly related to PHP because it was created for exchanging html pages and PHP simply expands the capabilities of both.

GET request is used to receive data and POST is used to send. (Remember that technically they work the same).

Therefore, in the context of PHP, based on this ideology, we did the following:
1. Every time you start PHP, superglobal arrays ($_GET, $_POST) are created by default.
2. If there is a question mark(?) in the query string. Everything after it is considered parameters GET request, they are presented in the format "key"="value" and the ampersand character (&) is used as a delimiter.
Example:
GET /index.php?name=Andrey&surname=Galkin
This is a query string, there are 2 parameters. these parameters will go into the $_GET array.
3. $_POST is filled in a different way. the contents of this array are filled from the "request headers". That is, from a place clearly hidden from view. The browser takes care of all the chores of creating such headers. Although sometimes something is edited in the headings manually.

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

For example, we have a login form with 2 fields: login and password.

Let's imagine that we are using the GET method. Then, when submitting the form, we will go to the following address /login.php?login=Andrey&password=123 You will agree that transmitting such information this way is not at all safe. Anyone can open your browser and, starting to enter the site address, they can see your passwords and logins from the history.

But if we specified the POST method, we would receive the following request:
POST /login.php (login=Andrey&password=123) what is in brackets would be hidden and not saved in any way in the browser.

To sum it up:
GET is to get a certain page in a certain form (sorting, current blog page, search bar, etc.).
POST - for sending data that does not affect the display of the page, in the sense that this data only affects the result of the script (logins, passwords, credit card numbers, messages, etc.).

And another good news is that they can be combined, for example
POST /index.php?page=login (login=Andrey&password=123) I think I have already explained enough what will come of this and which parameters will go into which array.

mob_info