如何从URL中提取参数并使用PHP将每个参数存储在一个新变量中[复制]

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;
  }
 }
php
dongma6326
dongma6326 它不是一个骗局。
接近 10 年之前 回复
dongshuo1257
dongshuo1257 不,这不对。
接近 10 年之前 回复

5个回答



PHP已内置此功能。</ p>

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

// example
if(isset($ sub1)){
echo $ sub1;
}
</ code> </ pre>

< p>有关详细信息,请参阅 parse_str </ p>
</ div>

展开原文

原文

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

duangan6731
duangan6731 否则称为$ _GET ...
接近 10 年之前 回复



  extract($ _ GET); 
</ code> </ pre>

很少 但是,这样做是个好主意,因为如果你在初始化“真实”变量时不小心会导致安全问题。 它本质上是 register_globals </ code> 所做的以及为什么 已弃用。</ p>
</ div>

展开原文

原文

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.

drhgzx4727
drhgzx4727 ......假设我没有误解这个问题,那就不是很清楚......
接近 10 年之前 回复

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)

dqys98341
dqys98341 或者简单的htmlspecialchars ......
接近 10 年之前 回复
duanpi7578
duanpi7578 filter_input(INPUT_GET,'sub')代替$ _GET ['sub']将有助于踩踏XSSness。
接近 10 年之前 回复

Its already been parsed by the environment:

Try:

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

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问