如何传递此变量并检查它是否匹配?

时间:2014-02-10 19:23:53

标签: php variables get isset

如何更正/简化并将其放入数组?

链接正在传递:somelink.php?w = a(或b,c,d)

我希望页面(somelink.php)确定是否设置了“w”,如果设置并且var匹配,则包括指定的页面。

<?php
if(isset($_GET['w'])&&($GET['w'] == "a")){include("1.htm");}
if(isset($_GET['w'])&&($GET['w'] == "b")){include("2.htm");}
if(isset($_GET['w'])&&($GET['w'] == "c")){include("3.htm");}
if(isset($_GET['w'])&&($GET['w'] == "d")){include("4.htm");}
else{include("1.htm");}
?>

5 个答案:

答案 0 :(得分:1)

使用switch语句:

if(isset($_GET['w']))
{
    switch($_GET['w'])
    {
        case 'a':    include("1.html");   break;
        case 'b':    include("2.html");   break;
        case 'c':    include("3.html");   break;
        case 'd':    include("4.html");   break;
        default:     include("1.html");   break;
    }
} else {
    include("1.html");
}

答案 1 :(得分:1)

一个简单的数组怎么样

$x=array('a'=>'1.html','b'=>'2.html');

然后

include $x[$GET['w']];

答案 2 :(得分:1)

尝试使用:

$w = $_GET['w'];
if(isset($w)) {
    switch(strtolower($w)) {
        case "a":
            include("1.htm");
        break;
        case "b":
            include("2.htm");
        break;
        case "c":
            include("3.htm");
        break;
        case "d":
            include("4.htm");
        break;
        default:
            include("not-found.htm");
        break;
    }
}

答案 3 :(得分:1)

像这样:

if(isset($_GET['w'])){
    switch($_GET['w']){
        case "a":
            include("1.htm");
        break;
        case "b":
            include("2.htm");
        break;
        case "c":
            include("3.htm");
        break;
        case "d":
            include("4.htm");
        break;
    }
}

但我不这样做。我这样做是为了使页面名称对应于从$ _GET变量中检索的值。这样你可以做这样的事情。

if(!empty($_GET['w'])){
    include($_GET['w'] . ".htm");
}

当然,你也需要对$ _GET var进行一点过滤,以确保它不会得到你不想要的东西。也许是这样。

$acceptable_values = array("some","acceptable","values");
if(!empty($_GET['w']) && in_array($_GET['w'],$acceptable_values) ){
    include($_GET['w'] . ".htm");
}

我确信你知道,将变量直接传递给include语句或数据库查询是一个可怕的想法。在这种情况下,请参见此处。

http://websec.wordpress.com/2010/02/22/exploiting-php-file-inclusion-overview/

答案 4 :(得分:0)

你可以做一些事情,让我们来看看其中一些。

<?php
$webpage = '';
if(isset($_GET['w']))
  $webpage = strtolower($_GET['w']);

switch($webpage)
{
  case 'b':
    include '2.html';
    break;
  case 'c':
    include '3.html';
    break;
  case 'd':
    include '4.html';
    break;
  default:
    include '1.html';
    break;
}

或者我们可以使用数组

<?php
$webpage = '';
if(isset($_GET['w']))
  $webpage = strtolower($_GET['w']);

$included_pages = array(
  'a' => '1.htm',
  'b' => '2.htm',
  'c' => '3.htm',
  'd' => '4.htm',
);

// Check inside our array
if(array_key_exists($webpage, $includes))
{
  include $included_pages[$webpage];
}
else
{
  // Couldn't find the site
  include '1.htm';
}