On a website, we often use forms to collect data, login/signup boxes for users, a search box to search through a web page, etc. So input fields are used to make the website interactive and to collect data. But we know that HTML can not store the data in a database so for that we use a backend scripting language like PHP.
URLs structure for GET method: In GET method, the URL contains all the data that is being sent from the front end. The URLs are like
https://geeksforgeeks.org/getdataurl?field1=data1&field2=data2&field3=data3...
Characteristic features of GET method URLs
- Generally, the URLs are very long
- The URL can be divided into two parts using the question mark ‘?’.
- Each field of the data is separated by ampersand ‘&’.
Read the Data: PHP has $_GET superglobal that accepts all the data from the URL and stores it as an array.
Syntax:
print_r($_GET);
Get data and store in an array with some extra information.
var_dump($_GET);
Example 1: In this example, we are going to use the print_r() function. This will give the output in the form of an array.
PHP
<?php     if (! empty ( $_GET ))   {       echo "Welcome to " . htmlspecialchars( $_GET [ 'username' ]). "!" ;       echo "<pre>" ;       print_r( $_GET );   }   else {       echo "No GET data passed!" ;   }   ?> |
Output:
Example 2: In this example, we are going to use the var_dump() function. This will give the output in the form of an array with some extra information. Â We are using the htmlspecialchars() function to get the data unaltered even if it is an HTML code.
PHP
<?php     if (! empty ( $_GET ))   {       echo "Welcome to " . htmlspecialchars( $_GET [ 'username' ]). "!" ;       echo "<pre>" ;       var_dump( $_GET );   }   else {       echo "No GET data passed!" ;   }   ?> |
Output:
If there is nothing after the question mark in the URL then the $_GET variable will return an empty array. $_GET is a global variable so it is available throughout the script, and we do not have to initialize it as a global variable. One more thing to remember is that if we want to pass a space-separated value in the URL then it is encoded and the space is converted to ‘+’ in the URL and when it is read using $_GET it is again decoded.