tags:

views:

56

answers:

5

Possible Duplicate:
How to grab URL parameters using PHP?

I was wondering how can I store each url parameter each in there own new variable when I don't know how deep the url parameters are?

Here is an example of a URL value.

http://www.localhost.com/topics/index.php?cat=3&sub1=sub-1&sub2=sub-2&sub3=sub-3&sub4=sub-4

Here is my PHP script.

 $url = $_SERVER['QUERY_STRING'];
 $query = array();

 if(!empty($url)){
   foreach(explode('&', $url) as $part){
   list($key, $value) = explode('=', $part, 2);
   $query[$key] = $value;
  }
 }
+1  A: 

PHP has this functionality already built in.

$query = parse_str($url);
extract($query)

// example
if(isset($sub1)) {
  echo $sub1;
}

see parse_str for more information

Ben Rowe
Otherwise known as `$_GET`...
ircmaxell
A: 

pass them as an array:

http://www.localhost.com/topics/index.php?cat=3&sub[1]=sub-1&sub[2]=sub-2&sub[3]=sub-3&sub[4]=sub-4

foreach($_GET['sub'] as $var=>$val){
   print $var."=".$val
}

(Disclaimer, vulnerable to xss)

Rook
`filter_input(INPUT_GET, 'sub')` in place of `$_GET['sub']` would help stomp out the XSSness.
tadamson
Or a simple `htmlspecialchars`...
ircmaxell
+2  A: 
extract($_GET);

It's rarely a good idea to do that though, since it can lead to security problems if you're not very careful with initializing your "real" variables. It's essentially what register_globals did and why it was deprecated.

deceze
...assuming I didn't misunderstand the question, it's not terribly clear...
deceze
A: 

Its already been parsed by the environment:

Try:

foreach($_GET as $key => $value)
{
    print "$key => $value\n";
}

Note: The $value part has already been decoded with urldecode(). So you actual get the value that was passed.

Note 2: If multiple values have been posted for the same key then $value is an array of all the values extracted from the URL.

http://Plop.com?p=1&p=2&p=3&p=fred

Then $value will be ( 1, 2, 3, 'fred');

Martin York
A: 

deceze has a good point, but extract is not as bad as it's made to sound. The issues come in using it without understanding what it does. You should prefix your extract variables to prevent any collisions.

<?php
    extract($_GET,EXTR_PREFIX_ALL,"extrprfx_");
?>

Edit I just realized that if you're going to pass a prefix, you should provide EXTR_PREFIX_ALL as the second parameter. Use EXTR_SKIP if you don't want to provide a prefix but don't want to override current variables.

Codeacula