d3b*_*g3r 5 php zend-framework
目前我在默认位置有一个Zend应用程序
www.example.com/{controller}/{action}
但是当用户从特定国家/地区访问时,如何检测其IP地址并将其重定向到此基于countryCode的网址
www.example.com/uk/{controller}/{action}?
为了检测用户访问的国家,我写了一个帮手:
require_once '../library/Ipinfo/ip2locationlite.class.php';
class Application_View_Helper_GetLocation extends Zend_View_Helper_Abstract
{
public function getLocation()
{
$ipLite = new ip2location_lite;
$ipLite->setKey('APIKEY');
//Get errors and locations
$locations = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
$errors = $ipLite->getError();
$country = strtolower($locations['countryName']);
return "$country";
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将返回国家/地区名称.如果用户正在从法国访问,我该如何重写网址以便网址成为example.com/france/{controller}/{action}?
将视图助手重构为控制器插件并重定向。
控制器插件可以在请求调度循环的早期执行,因此您可以在加载和渲染任何控制器之前拦截请求并重定向到另一个响应。下面的示例(警告,可能包含错误!)
class App_Plugin_DetectCountry extends Zend_Controller_Plugin_Abstract {
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$ipLite = new ip2location_lite;
$ipLite->setKey('APIKEY');
//Get errors and locations
$locations = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
$errors = $ipLite->getError();
$country = strtolower($locations['countryName']);
//Check if set country equals detected country
if (!isset($_COOKIE['country']) || $country !== $_COOKIE['country']) {
$_COOKIE['country'] = $country;
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->gotoUrl($country . '/' . $request->getControllerName() . '/' . $request->getActionName());
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
645 次 |
| 最近记录: |