Php get all get parameters. External variables (variables outside of PHP). Passing Variables to PHP Using the POST 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 stream_get_contents function (similar to file_get_contents ) or a while loop to read the content 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. As a rule, it should not be greater than 8192 (8*1024).

from get(9)

What is a "less code" way to get parameters from a URL query string that is formatted like this?

www.mysite.com/category/subcategory?myqueryhash

The output should be: myqueryhash

I know about it:

www.mysite.com/category/subcategory?q=myquery

Answers

This code and notation are not mine. Evan K resolves a multi-valued job of the same name with a user-defined function;) taken from:

The above example outputs:

Hello Hannes!

If you want to get the entire query string:

$_SERVER["QUERY_STRING"]

Also, if you are looking for the current filename along with the query string, you just need the following

Basename($_SERVER["REQUEST_URI"])

This will give you information like the following example

file.php? arg1 = value & arg2 = value

And if you also need the full path to the file starting from root like /folder/folder2/file.php?arg1=val&arg2=val then just remove the basename() function and just use overlay

$_SERVER["REQUEST_URI"]

Thanks @K. Shahzad This helps when you want to rewrite the query string without any rewriting additions. Let's say you rewrite /test/? X = y in index.php? Q = test & x = y and you want to get the query string.

Function get_query_string())( $arr = explode("?",$_SERVER["REQUEST_URI"]); if (count($arr) == 2)( return ""; )else( return "?".end($ arr)."
"; ) ) $query_string = get_query_string();

The PHP way to do this is to use the parse_url function, which parses a URL and returns its components. Including the query string.

$url = "www.mysite.com/category/subcategory?myqueryhash"; echo parse_url($url, PHP_URL_QUERY); # output "myqueryhash"

Here is my function to recover parts of the REFERRER query string.

If the calling page already had a query string in its own , and you need to return to that page and want to send some, not all, of those $_GET vars (e.g. page number).

Example: the Referrer query string was?foo=1&bar=2&baz=3 calling refererQueryString("foo" , "baz") returns foo=1&baz=3" :

Function refererQueryString(/* var args */) ( //Return empty string if no referer or no $_GET vars in referer available: if (!isset($_SERVER["HTTP_REFERER"]) || empty($_SERVER["HTTP_REFERER" "]) || empty(parse_url($_SERVER["HTTP_REFERER"], PHP_URL_QUERY))) ( return ""; ) //Get URL query of referer (something like "threadID=7&page=8") $refererQueryString = parse_url( urldecode($_SERVER["HTTP_REFERER"]), PHP_URL_QUERY); //Which values ​​do you want to extract? (You passed their names as variables.) $args = func_get_args(); //Get "" strings out of referer" s URL: $pairs = explode("&",$refererQueryString); //String you will return later: $return = ""; //Analyze retrieved strings and look for the ones of interest: foreach ($pairs as $pair ) ( $keyVal = explode("=",$pair); $key = &$keyVal; $val = urlencode($keyVal); //If you passed the name as arg, attach current pair to return string: if( in_array($key,$args)) ( $return .= "&". $key . "=" .$val; ) ) //Here are your returned "key=value" pairs glued together with "&": return ltrim($return,"&"); ) //If your referer was "page.php?foo=1&bar=2&baz=3" //and you want to header() back to "page.php?foo=1&baz=3" //(no "bar", only foo and baz), then apply: header("Location: page.php?".refererQueryString("foo","baz"));

Microsoft Support states: "The maximum URL length is 2083 characters in Internet Explorer."

IE has been having problems with URLs for longer. Firefox seems to work fine with >4k characters.

Web programming for the most part is just the processing of various data entered by the user - i.e., processing HTML forms.
There is probably no other language like PHP that would make the task of processing and parsing so much easier for you, i.e. variables that came from (from the user's browser). The fact is that all the necessary capabilities are built into the PHP language, so you don’t even have to think about the features of the HTTP protocol and think about how to send and receive POST forms or even download files. The PHP developers have provided for everything.

Here we will not dwell in detail on the mechanism of the HTTP protocol, which is responsible for delivering data from the browser to the server and back; a special section is devoted to this PHP and HTTP. The principles of working with HTML forms are also discussed in depth.

Now we will consider these mechanisms only from an applied point of view, without delving into theory.

In order to receive data from users, we need interactive interaction with them.

Now let’s try to write a script that takes a username as parameters and outputs:

"Hello, !".

First, let's look at the simplest way to pass a name to a script - directly typing it in the URL after the ? - for example, in the format name=name . Here's an example:

http://localhost/script.php?name=name

Our script needs to recognize the name parameter. That is, to put it simply, the script (script) must accept the name parameter in the form of the name variable, and then display the string “Hello, !” in the user’s browser. You can do it this way:

We write a script that takes the name parameter and displays the result in the user’s browser, and then saves it under the name script.php:

In our example, we used the predefined variable $_GET["name"] to "receive" the name parameter. Now, by passing the parameter name=Sasha via a GET request, we will get the following result:

Hello Sasha!

Now let’s try to pass the name parameter not from the browser query string, but through an HTML form. We create an HTML document with the following content:


Name:

Now let's save this HTML document on our test server (localhost) under the name send.html in the same directory where we already saved the script.php script.

Now we launch the HTML document in the browser:

http://localhost/send.html

Enter the name in the field and press the “GO!” button. The form will pass the name parameter to our script script.php via a GET request. If you did everything correctly and your web server is working normally, you will see the name you entered in the form field! In the browser's address bar you will see the path and the name parameter you passed.

Now we need to understand how we can pass many parameters, at least two to start with.

So, we need the script to output the following:

"Hello! You are old!"

That is, we need to pass 2 parameters to the script: name and age.

Now we will write a script.php that takes two parameters: name and age, as well as an HTML document with a form that will pass these two parameters to our new script:

And here is the HTML document send.html, with which we will pass the name and age parameters to our script:



Enter your name:

Enter age:



Now our script takes two parameters name and age and displays the result in the browser in the format: “Hello,! Are you old!”

Pay attention to the browser address bar after passing the parameters to the script, it will look something like this (without Cyrillic URL encoding):

http://localhost/script.php?name=Sasha&age=23

Depending on your interpreter settings, there are several ways to access data from your HTML forms. Here are some examples:

//In the form, using the get method, we send the value 1 through a hidden field Send a request

get.php file

Php request post

The Php post request is also sent through a form, only the attribute in the form tag will be method="post" . And we will receive the data in the specified file from the post $_POST["search"] array and immediately give an example.

Task: send data from index.php using the POST method to the server in the get.php file and receive it back, if the data sending field is empty, display a message about the empty field. Let's start the solution with index.php

Search query

Fill in the request field

Entered query:

Send request

get.php file

AJAX Array Passing

Let's accomplish the same task using ajax. Actually, ajax is a technology related to javascript, but as part of the note on transferring data to the server, we will also touch on this technology. Of course, ajax is a topic for a separate article. During the request process, we will also display a gif of the loading indicator. We also have two files index.php and get.php. Index.php file. Don't forget to connect jquery. Please note that to hide the gif when the page first loads, assign the style display: none to the box block

$(document).ready(function())( //we attach an event to the submit button $(".submit").click(function())( $.ajax(( //how we will transfer data type: "GET", / /where we pass url: "get.php", //what data we pass data: (flag: 1), //event before sending ajax beforeSend: function())( //display a gif $(".box").show( ); ), //event after receiving a response, //get an array in data success: function(data)( //hide the gif $(".box").hide(); var html = ""; //f- i JSON.parse translates json data into an object var dt=JSON.parse(data); for (var i = 0; i

The get.php file. We receive data from the get array into the file and pass the array from php to javascript. To pass an array to php to js, ​​it needs to be converted to json format. To do this, we use the php function json_encode. After recoding, json is sent via php means, specifically calling echo.

I have a URL structure with a query string and a parameter called position.

Http://computerhelpwanted.com/jobs/?occupation=administrator&position=network+administrator

I also have a form select dropdown with the form select name position .

Select Occupation Administrator Select Position Network Administrator

When the user makes a selection, it sends the parameter values ​​to the action attribute with select name="position" as the parameter to use in the query string.

My question is how do I access the form selection values ​​separately from the query string values?

I'm using the _GET method to call a value from a query string parameter.

$position = isset($_GET["position"]) ? ($_GET["position"]) : "";

Obviously this gets its value from the URL structure, not the form element. Or maybe it is, not sure. But testing it, I seem to have come to the conclusion that it is getting it by URL and not by form.

How can I access the form's select value when comparing in my PHP?

Update

I have a problem with the canonical URL specified in the header.

That is how it should be

the only difference is the - and + in the query string.

Not all my query strings have +. Some have -. But I'm showing content on both URLs, regardless of whether it has a - or +. Either way, both URLs receive the same page content.

But since the canonical is created dynamically from the URI and not from the value of the form element, there are 2 different canonical characters on both content pages.

Using _Get('value') retrieves the value from the query string instead of the form element. I know this because the form element value has a space between network administrator which gets urlencoded when the form submits as network+administrator . So if I can compare with the form element value I can set the correct canonical one.