2014-11-01 66 views
0

我目前使用PHP調用geoip數據庫,以基於其IP地址解析爲的狀態重定向用戶。用PHP排除JavaScript /白名單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中都不流利,所以非常感謝幫助。

謝謝

回答

1

如果這段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> 
+0

謝謝你的迴應。我剛剛意識到這將會在.js文件中的自己的目錄中。任何方式來使用PHP不參考文件,如果它匹配的地址?謝謝你,亞當。 – brenda 2014-11-02 17:39:19

+0

@brenda啊,好的。我已經更新了我的答案。 – Entity 2014-11-03 15:28:10

+0

@brenda很高興能幫到你!如果這解決了你的問題,我會很感激,如果你點擊我的答案右邊的小複選標記:) – Entity 2014-11-03 21:22:52