我目前使用 PHP 调用 geoip 数据库,根据用户的 IP 地址解析到的状态来重定向用户。
我现在切换到调用 maxmind 数据库的 javascript API。
问题:我不知道如何将自己的 IP 地址列入白名单。
这是不再使用的旧 PHP 代码:
include_once("/home/censor/geoip/geoipcity.inc");
$gi = geoip_open("/home/censor/geoip/GeoLiteCity.dat",GEOIP_STANDARD);
$record = geoip_record_by_addr($gi,$_SERVER["REMOTE_ADDR"]);
geoip_close($gi);
if((trim($record->region)=="WA") && ($_SERVER["REMOTE_ADDR"]!="11.111.111.111")) {
header("Location: http://www.google.com"); /* Redirect browser */
exit;
}
11.111.111.111 是列入白名单的 IP 地址。
这是新的 JavaScript 代码:
<script src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js" type="text/javascript"></script>
<script type="text/javascript">
var redirect = (function () {
/* This implements the actual redirection. */
var redirectBrowser = function (site) {
var uri = "http://" + site + ".google.com/";
window.location = uri;
};
/* These are the country codes for the countries we have sites for.
* We will check to see if a visitor is coming from one of these countries.
* If they are, we redirect them to the country-specific site. If not, we
* redirect them to world.example.com */
var sites = {
"WA": true
};
var defaultSite = "www";
var onSuccess = function (geoipResponse) {
/* There's no guarantee that a successful response object
* has any particular property, so we need to code defensively. */
if (!geoipResponse.city.iso_code) {
redirectBrowser("www");
return;
}
/* ISO country codes are in upper case. */
var code = geoipResponse.city.iso_code.toLowerCase();
if ( sites[code] ) {
redirectBrowser(code);
}
else {
redirectBrowser("www");
}
};
/* We don't really care what the error is, we'll send them
* to the default site. */
var onError = function (error) {
redirectBrowser("www");
};
return function () {
geoip2.city( onSuccess, onError );
};
}());
redirect();
</script>
有人可以为我提供一种使用新代码将 IP 地址列入白名单的方法吗?我对 PHP 或 Javascript 一点也不流利,所以非常感谢您的帮助。
谢谢
最佳答案
如果此 javascript 代码内联在 PHP 文件中(听起来确实如此),您可以替换它:
if ( sites[code] ) {
这样:
if (sites[code] && "<?php echo $_SERVER['REMOTE_ADDR']; ?>" !== "11.111.111.111") {
<小时/>
OP 已指定 JavaScript 代码不是内联。在这种情况下,您可以修改代码:
if ( sites[code] ) {
对此:
if (sites[code] && userIp !== "11.111.111.111") {
其中 11.111.111.111
是您要列入白名单的 IP。然后,在您的 PHP 中包含以下脚本:
<script>
var userIp = "<?php echo $_SERVER['REMOTE_ADDR']; ?>";
</script>
关于javascript - 使用 PHP 排除 javascript/白名单 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685681/