Get parameter value from select form instead of query string. External variables (variables outside PHP) Pass all get parameters to php

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 function parse_url, 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 restore parts lines request REFERRER .

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.

So we continue our study again PHP basics and in this article we will get acquainted with ways of passing variables in PHP, namely with GET and POST methods. Each of them has its pros and cons, and is used in appropriate situations, which will be discussed in this article. We'll also look at code examples that demonstrate how the POST and GET methods work.

Passing Variables Using the GET Method

This variable passing method is used in PHP to pass variables to a file using the address bar. That is, variables are transmitted immediately through the browser address bar. An example would be, for example, a link to an article in WordPress without using CNC (SEF), which looks something like this:

Https://site/?p=315

That is, in this case, the $p variable with the value 315 is passed. Now let's look at the GET method in more detail using an example. Let's say we need to pass three variables $a, $b and $c to the file GET method and display their sum on the screen. You can use the following code for this.

$a = $_GET["a"]; $b = $_GET["b"]; $c = $_GET["c"]; $summa = $a + $b + $c; echo "Sum $a + $b + $c = $summa";

Since all variables will be placed in global array GET(), then we first assign our variable values corresponding elements of the GET array. We do this at the very beginning to avoid various errors when passing variables. Next, to demonstrate the work, we write an arbitrary formula and display the result on the screen.

To test the GET method, simply add a question mark “?” to the file link. and through the ampersand “&” list the variables with their values. Let us have a file get.php, which lies at the root of the site. In order to transfer variables to a file, just write the following in the address bar.

Https://site/get.php?a=1&b=2&c=3

As you can see from the example, first we add a question mark immediately after the file name. Next, we register the variable and indicate its value using equals. After this, we list other variables in the same way through the ampersand. Now, when we click on this link, we will see the sum of the variables $a, $b and $c.

This method is very simple and does not require creating additional files. All necessary data comes directly through the address bar of the browser.

Well, now let's move on to the second method of passing variables in PHP - to the POST method.

Passing Variables to PHP Using the POST Method

This method allows you to secretly transfer variables from one file to another. As you already understood, two files are usually used for these purposes. The first contains a form for entering initial data, and the second contains an executive file that accepts variables. For demonstration, let's look at the following code.

Code of the first file with the form for submitting data. Let's give it the name post-1.php

  • action – specify the file to which the variables will be transferred.
  • method – method of passing variables. In our case, this is the POST method.
  • name – name of the form. At the same time, a variable with the same name will be transferred to the file.

Text fields:

  • name – variable names. In our case, this is the first and last name (name and lastname variables).
  • type – field type. In our case, this is a text field.
  • name – the name of the button and the variable that will be passed along with other variables.
  • type – button type. In our case, this is a button for sending data.
  • value – text on the button.

The code of the second file, which will serve as a variable receiver. Let's call it post-2.php

$name = $_POST; $lastname = $_POST; echo "The values ​​of the variables passed by the POST method are $name and $lastname";

As with the GET method, we first assign the values ​​of the corresponding elements to the variables global arrayPOST. Next, for clarity, we display these variables on the screen using .

Now when we load the first file, the form will load. After entering the data, click on the “Submit” button, as a result of which a page with a second file will open in a new tab, which will display the values ​​​​written in the form on the previous page. That is, the values ​​of variables from the first file will be transferred to the second file.

This concludes this article about passing variables in PHP. If you don’t want to miss the appearance of other articles on the blog, I recommend subscribing to the newsletter in any convenient way in the “Subscription” section or using the form below.

That's all. Good luck and success in mastering the basics of PHP.

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 symbols 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 ).

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 sign ? - for example, in the format name=name. Here's an example:

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

Our script needs to recognize the parameter name. That is, to put it simply, the script (script) must accept the parameter name as a variable name, and then display the string “Hi,<имя>!". You can do it this way:

We write a script that accepts a parameter name and outputting the result to the user's browser, and then saving it under the name script.php:

echo "Hello, $_GET["name"] !";
?>

In our example we used a predefined variable $_GET["name"] to "accept" the parameter name. Now, having passed through GET-query parameter name=Sasha, we get the following result:

Hello Sasha!

Now let's try to pass the parameter name not from the browser's request line, 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 have the script saved script.php.

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 send a parameter via a GET request name our script script.php. 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 address bar of the browser you will see the path and the parameter you passed name.

Now we need to understand how we can pass many parameters, for starters at least two.

So, we need the script to output the following:

"Hello,<имя>! To you<возраст>years!".

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

Now we will write the script script.php, which 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:

echo "Hello, $_GET["name"]! You are $_GET["age"] years old!";
?>

And here is the HTML document send.html, with which we parameters name And age Let's pass it to our script:



Enter your name:

Enter age:



Now our script takes two parameters name And age and displays the result of the format in the browser: “Hello,<имя>! To you<возраст>years!".

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:

// Available since PHP 4.1.0

Echo $_GET["username"];
echo $_POST["username"];
echo $_REQUEST["username"];

Internet