Sachin
Sachin

Reputation: 3782

Parse a URL to extract all the GET variables in the URL

How can I parse the current url to get all the GET variables from it. Although there is a function by the name of

HTTP_GET_VARS

But the documentation says it is deprecated so I do not want to use that. I want to do something like this, if I have a url as

www.example.com/variables.php?var1=1&var2=2&var3=3

I want to extract all the GET variable in an array vars such that I have the name of the variable as well it's value in the url so tha I can use them while building a different url as

www.example.com/new_variables.php?vars[var_name]=vars[var_value]

I can go through all the variables in a for loop and incrementally build the url. What I mean is that using GET I have to see if the value is set for each of the variables that I expecting, but what I want is to get the list of all the GET variables which are set. My ulr can contain 3-4 variable which may not be set all the time. I don't want to check if all 4 are set at any point of time, I just want to filter my query based on whichever parameters are set.

Upvotes: 0

Views: 15889

Answers (2)

Ben
Ben

Reputation: 21249

Use parse_str

e.g.

parse_str($_SERVER['QUERY_STRING'], $output);

EDIT: And you can use its reverse friend http_build_str to do the opposite

Upvotes: 6

Carsten
Carsten

Reputation: 18446

The $HTTP_GET_VARS variable is marked as deprecated because the newer $_GET variable was introduced. That's the one you should use. It contains all paramters from the query string in an associative array, e.g. $_GET['var1'] would be 1 in your case.

If you want to construct the new URL with all GET parameters, you could loop over them, or you could just copy the current query string:

$new_url = "new_variables.php?" . $_SERVER['QUERY_STRING'];

Upvotes: 1

Related Questions