phphtmladdress-bar

How to get data from address bar in php


I know the question seems kind of misleading or confusing, but here's what I mean. If you have a link in HTML, I read that you can do something like this:

<a href="index.html?hi=0">

The above link is supposed to take you to the same page, but with a new value of hi that is equal to 0. First off, is it true that you can do that? You could also change the value of hi through different links by using the same code as above.

Here's the sort of second part to my question. How can you retrieve that value in php? I saw that you could, but I forgot how. For example, what if the link to the page was index.html?hi=2. How could you retrieve the value of hi in php? Anyways, I hope you can solve my problem and understand it. Thanks in advance!


Solution

  • Everything after the ? in a URL is called the Query String, and yes you can call the same page with different data there.

    PHP will automatically parse the Query String and place it's values in the superglobal $_GET for your convenience, so for instance in index.php?hi=1 you can read $_GET['hi'] to get the value of "hi".

    Multiple variables can be passed this way, like index.php?foo=1&bar=2 will deliver $_GET['foo'] with value 1 and $_GET['bar'] with value 2.

    You can simply use & to separate variables in most cases, but to ensure correct formating, use http_build_query() to convert an associative array into a valid Query String.