How to access data sent through URL with GET method in PHP ?
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
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.
Get data and store in an array with some extra information.
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.
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.
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.
Please Login to comment...