我不熟悉PHP,但我需要创建一个简单的页面来暂时重定向内部用户,直到修复生产问题。
如果用户的IP地址以"10."
,"192."
或"172."
开头,那么我需要将它们重定向到另一台服务器。如果用户的IP地址不符合此条件,那么我需要显示一条消息,告知用户该站点已关闭以进行维护。
有人可以帮我这个吗?
答案 0 :(得分:6)
您可以使用preg_match()
查看用户的地址($_SERVER['REMOTE_ADDR']
)是否以10.
,192.
或172.
开头:
if(preg_match('/^(10|192|172)\./', $_SERVER['REMOTE_ADDR']))
{
header('Location: http://example.com');
die;
}
echo 'Site down for maintenance.';
答案 1 :(得分:2)
$chunks = explode('.', $_SERVER['REMOTE_ADDR']);
$whitelist = array(10, 192, 172);
$server = "http://example.com";
if(in_array($chunks[0], $whitelist))
{
//redirect to another server
header("Location: " . $server);
die();
}
else
{
//Show maintenance message
die("The site is down for maintenance.");
}
答案 2 :(得分:1)
您无法通过IPv4地址的第一个八位字节可靠地识别本地IP地址。幸运的是,PHP已经为我们处理了所有这些。我知道OP只询问IPv4,但这个解决方案也包括IPv6和保留地址。
/**
* Function returns true if IP Address is identified as private or reserved
*
* Uses REMOTE_ADDR, a reliable source as TCP handshake is required, most others can be spoofed
*
* FILTER_FLAG_NO_PRIV_RANGE:
* Fails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.
* Fails validation for the IPv6 addresses starting with FD or FC.
*
* FILTER_FLAG_NO_RES_RANGE:
* Fails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24 and 224.0.0.0/4.
* This flag does not apply to IPv6 addresses.
*/
function isPrivateIp()
{
return !filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}
/*Using function to get OP desired result*/
if (isPrivateIp() === true) {
$server = 'http://example.com';
//redirect to another server
header("Location: $server");
} else {
//Show maintenance message
echo 'The site is down for maintenance.';
}
exit;
答案 3 :(得分:0)
<?php
// Settings
$toRedirect = array (10, 172, 192);
$redirectAddress = 'http://wherever.com/';
$maintenanceMessage = 'The site is down for maintenance';
// Split the IP address into octets
list($oct1, $oct2, $oct3, $oct4) = explode('.', $_SERVER['REMOTE_ADDR']);
// Send local clients to redirect address
if (in_array($oct1, $toRedirect)) {
header('HTTP/1.1 307 Temporary Redirect');
header('Location: '.$redirectAddress);
}
// Exit with the maintenance message.
// We can send this everyone in case the redirect fails
exit($maintenanceMessage);
答案 4 :(得分:0)
嗯,你可以这样做:
$ip = $_SERVER['REMOTE_ADDR']; //get IP address
$toRedirect = array(10,192,172);
$parts = explode('.', $ip);
$id = $parts[0];
if(in_array($id, $toRedirect)) {
//do redirect
}