开发者

How to extract parameters from a URL and storing each in a new variable using PHP [duplicate]

开发者 https://www.devze.com 2023-01-11 20:30 出处:网络
This question already has answers here: 开发者_如何学编程Closed 12 years ago. Possible Duplicate:
This question already has answers here: 开发者_如何学编程 Closed 12 years ago.

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;
  }
 }


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.


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


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)


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');


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消