我尝试制作一个基于 ip 的拒绝列表,该列表将 ip 编号存储在 mysql 中。基本上,如果用户的 ip 在数组中,我尝试 header 重定向,但它不起作用。怎么了?
$ip_array = array();
$ip_ban_query = mysql_query("SELECT ip FROM banned_ips");
while ($deny = mysql_fetch_assoc($ip_ban_query)){
$add_ip = $deny['ip'];
$ip_array[] = $add_ip;
}
if (in_array ($_SERVER['REMOTE_ADDR'], $ip_array)) {
header("Location: http://www.google.com/");
exit();
}
最佳答案
我们可以在这里大大简化您的代码..降低复杂性几乎总是可以消除错误。 :)
// There are several different methods to accomplish this, and you really
// should be using statements here, but both are out of scope of this question.
$ipBanQuery = sprintf("SELECT ip FROM banned_ips WHERE ip = '%s'", mysql_real_escape_string($_SERVER['REMOTE_ADDR']));
$result = mysql_query($ipBanQuery);
if (mysql_num_rows($result)) {
header('Location: http://www.google.com/');
exit();
}
这还取决于您在何处调用此代码。请特别确保在向浏览器输出任何内容之前调用此函数 - 杂散空格、HTML 或其他调试信息将阻止发送任何其他 header 。检查网络服务器的错误日志,看看是否有异常情况发生。
关于php header 位置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9611998/