从GeoPlugin PHP结果缓存IP

时间:2015-09-30 12:03:27

标签: php

我正在使用GeoPlugin来测试访问者所浏览的国家/地区,并根据结果重定向它们。目前我在每个页面上都有代码,因此每个页面都会发出相同的请求。是否可以按IP地址执行一次查找并将结果缓存一段时间,以减少对GeoPlugin的请求数。到目前为止我的代码是:

<?php 

$meta = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));

if (($meta['geoplugin_countryCode']=='CN' || 
     $meta['geoplugin_countryCode']=='IR'
    )&&(        
     $meta['geoplugin_request']!=='1.2.3.4'
   ))       
{
    header('Location: http://google.com', true);
    die();
}

?>

提前致谢!

2 个答案:

答案 0 :(得分:1)

我的最终代码如下,使用上面建议的会话:

<?php

session_start();

if( isset( $_SESSION['geoplugin'] ) )

{
  $meta=$_SESSION['geoplugin'];
    echo "Using a stored session";
}

else

{
   $meta = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));

   $_SESSION['geoplugin'] = $meta;

    echo "Using a new session";
}

if (
(
    $meta['geoplugin_countryCode']=='CN' || 
    $meta['geoplugin_countryCode']=='HK' ||
    $meta['geoplugin_countryCode']=='TW' ||
    $meta['geoplugin_countryCode']=='AP' ||
    $meta['geoplugin_countryCode']=='ID' ||
    $meta['geoplugin_countryCode']=='KP' ||
    $meta['geoplugin_countryCode']=='KR' ||
    $meta['geoplugin_countryCode']=='MN' ||
    $meta['geoplugin_countryCode']=='MY' ||
    $meta['geoplugin_countryCode']=='PG' ||
    $meta['geoplugin_countryCode']=='PH' ||
    $meta['geoplugin_countryCode']=='VN' ||
    $meta['geoplugin_countryCode']=='IN' ||
    $meta['geoplugin_countryCode']=='BD' ||
    $meta['geoplugin_countryCode']=='RK' ||
    $meta['geoplugin_countryCode']=='RU' ||
    $meta['geoplugin_countryCode']=='PL' ||
    $meta['geoplugin_countryCode']=='BG'
)

&&
(       
    $meta['geoplugin_request']!=='1.2.3.4'
)
)

{

header('Location: https://mywebsite.co.uk/denied', true);
}

$status = session_status();

if($status == PHP_SESSION_DISABLED)
{
echo "Session is Disabled";
}
else if($status == PHP_SESSION_NONE )
{
 echo "Session Enabled but No Session values Created";
}
else
{
echo "Session Enabled and Session values Created";
}

?>

答案 1 :(得分:0)

我喜欢会话存储的想法,但这是一个更具持久性的缓存,它对于不存储会话数据并且使用IP地址池的机器人等也很有用。

qs, created = Learner.objects.get_or_create(user=self.request.user)
formset = LearnerFormSet(queryset=qs)