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:
The form has attributes, I will list the most common ones:
Let's create a form:
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: