PHP Tutorial PHP Advanced PHP References

PHP $_GET Variable



The PHP $_GET is a built-in super global variable which is always available in all scopes. It is used to collect form data after submitting an HTML form with HTTP GET method. Information sent using a HTML form with the GET method is visible to everyone. All variable names and values are displayed in the URL with page and the encoded information are separated by the ? character (known as QUERY_STRING). Each variable name and value pair is separated by ampersand (&) sign.

An example URL with two variables ("variable1" and "variable2") sent using GET method will be similar to:

http://www.test.com/index.htm?variable1=value1&variable2=value2

The HTTP GET method is restricted to send about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page.

The data sent by HTTP GET method can be accessed using QUERY_STRING environment variable. The $_GET associative array is used to access all the sent information using the GET method.

The HTML form

Consider the example below where test.php contains following code. This page will send the GET variables ("name" and "age") to the action script, welcome.php.

<html>
<body>
   
  <form action="welcome.php" method="GET">
    Name: <input type = "text" name = "name" />
    Age: <input type = "text" name = "age" />
    <input type = "submit" />
  </form>
      
</body>
</html>

The test.php will look similar to:

The HTML form

The action script

Now, consider the welcome.php as the action script page which contains the following code:

<html>
<body>
   
  <?php
    echo "Hello ". $_GET['name']. "<br>";
    echo "You are ". $_GET['age']. " years old.";
  ?>
      
</body>
</html>

Result

If the following input is provided to the test.php:

The HTML form

When "submit" button is clicked, it will open the welcome.php script with the URL similar to (note the query string):

http://www.test.com/welcome.php?name=John&age=25

The URL contains the following result:

The HTML form

Example: $_GET example

The example below demonstrates the above discussed concept.

<html>
<body>
   
  <form action="welcome.php" method="GET">
    Name: <input type = "text" name = "name" />
    Age: <input type = "text" name = "age" />
    <input type = "submit" />
  </form>
      
</body>
</html>

Note: The HTTP GET method is used for sending non-sensitive data and it should NEVER be used for sending sensitive information.

Note: The HTTP GET method can not be used to send binary data, like images or word documents, to the server.

❮ PHP - Predefined Variables