朋友,请不要生气,但我宁愿问“这段代码有什么正确的吗?”
<?php
$check = array ("85.49.","85.62.");
foreach($check as $var) {
// Here you use the deprecated ereg instead of preg_match or, better, strpos
// However, the regular expressions would be wrong - what if 192.85.49.3 comes by?
if (ereg($var, $_SERVER['REMOTE_ADDR'])) {
$intruder = 0;
}
else {
$intruder = 1;
}
// Here you do not close the foreach, so that the following code gets executed
// repeatedly
// Here you place a ; after the if, so the if body is empty and bugger off gets
// triggered always.
// Which changes little, since $intruder = 0 is an assignment (use == instead)
// (see note)
if ($intruder = 0);
echo 'bugger off';
}
// Anyway, logically "$intruder == 0" means "NOT an intruder", so you are actually
// telling friends to bugger off and welcome intruders :-)
else{
echo 'welcome';
}
?>
注意:这可能是巫毒编程(我在 Maguire 的“Writing Solid Code”中找到它),但我认为您可能会养成以另一种方式检查值的习惯:
如果(0 == $intruder)
这样,如果您再次删除 =,它不会创建一个新的语句来做您不想要的事情,但它会变成一个语法错误,使自己立即可见。
无论如何,您想要的代码应该是:
<?php
$check = array ("85.49.","85.62.");
$matches = false;
foreach($check as $var)
{
if (0 === strpos($_SERVER['REMOTE_ADDR'], $var))
{
$matches = true;
// There is one match, no sense in checking further
break;
}
}
if ($matches)
{
// He is in our little list - tell him something
print "You match.";
}
?>