Wordpress IP限制w /标题位置重定向

时间:2012-09-21 04:16:52

标签: php wordpress

我有一个wordpress网站我正试图锁定一组IP。我在index.php中使用以下代码作为第一件事:( IPs在这里混淆)

$matchedIP = 0;
$IP = $_SERVER['REMOTE_ADDR'];

$validIPs = array("x.x.x.x", "x.x.x.x", "x.x.x.x", "x.x.x.x", "x.x.x.x");

foreach($validIPs as $validIP)
{
    if($IP == $validIP)
    {
        $matchedIP = 1;
    }
}

if($matchedIP == 0)
{
    header('Location: http://google.com.au');
}

IP检查工作正常,因为各种断言可以确认。什么是行不通的是重定向,从未发生过。完整的index.php如下:

<?php

$matchedIP = 0;
$IP = $_SERVER['REMOTE_ADDR'];

$validIPs = array("x.x.x.x", "x.x.x.x", "x.x.x.x", "x.x.x.x", "x.x.x.x");

foreach($validIPs as $validIP)
{
    if($IP == $validIP)
    {
        $matchedIP = 1;
    }
}

if($matchedIP == 0)
{
    header('Location: http://google.com.au');
}

/**
 * Front to the WordPress application. This file doesn't do anything, but loads
 * wp-blog-header.php which does and tells WordPress to load the theme.
 *
 * @package WordPress
 */

/**
 * Tells WordPress to load the WordPress theme and output it.
 *
 * @var bool
 */
define('WP_USE_THEMES', true);

/** Loads the WordPress Environment and Template */
require('./wp-blog-header.php');

//require('./phpinfo.php');

奇怪的是,当评论出wordpress blog-header需要并将一个require包括在一个简单的phpinfo页面时,重定向就会按预期运行。

我是否误解了PHP处理在某种程度上的运作方式?当然它应该在它考虑加载下面的任何所需文件之前点击重定向?

编辑:Windows IIS7后端,PHP版本5.2.17,Wordpress版本3.4.2

2 个答案:

答案 0 :(得分:0)

如果要进行正确的重定向,则必须在header - 指令后终止脚本执行:

if(!in_array($IP, $validIPs))
{
    header('Location: http://google.com.au');
    exit(0);
}

原因是,如果让Wordpress继续执行,它将发送HTTP状态代码200,浏览器将忽略Location标头。只有HTTP状态代码的子集才会使用Location标头。

exit到位后,PHP停止执行并自动发送302 HTTP状态,告知浏览器重定向到Location标题中指定的URL。

答案 1 :(得分:0)

你不需要for循环

<?php

$matchedIP = 0;
$IP = $_SERVER['REMOTE_ADDR'];

$validIPs = array("x.x.x.x", "x.x.x.x", "x.x.x.x", "x.x.x.x", "x.x.x.x");

if(in_array($IP, $validIPs))
{
    header('Location: http://google.com.au');
    exit(0);
}

?>