最近在做关于方维的项目,方维的根据ip定位思路大概是这样的,在路由分发控制器前载入了一个叫做user_init.php的文件,查看这个人第一次访问时cookie里面和url里面是否有关于城市的记录,如果没有的话,自动跳到城市选择页,
//首次访问跳转到城市选择if(!isset($_REQUEST['act']) && intval(a_fanweC("FIRST_VISIT_CITY"))==1&&!isset($_COOKIE['had_select_city'])&&!isset($_REQUEST['cityname']) && strtolower($_REQUEST['m'])=="index"){ redirect2(a_u("City/more"));}
然后封装了一个叫getCurrentCityID的函数。如果url没有传城市时,就从cookie里的历史记录里面去找。如果cookie里面没有历史记录的话,就调用一个根据ip地址定位所在城市,然后传入session里。
function getCurrentCityID(){ if(!empty($_REQUEST['cityname'])) { $cityName = trim($_REQUEST['cityname']); $currentCity = $GLOBALS['db']->getRowCached("SELECT id,py FROM ".DB_PREFIX."group_city where py = '".$cityName."' and verify=1 and status =1"); if($currentCity){ setcookie('cityID',base64_encode(serialize($currentCity['id']))); $_SESSION['cityID'] = $currentCity['id']; $_SESSION['cityName'] = $currentCity['py']; return $currentCity['id']; } } $cityID = intval($_SESSION["cityID"]); if($cityID > 0){ return $cityID; } if ($cityID==0){ $cityID = intval(unserialize(base64_decode($_COOKIE['cityID']))); } //动态定位 if($cityID==0) { //$ip = get_ip(); $city_list = $GLOBALS['db']->getAllCached("SELECT id,name FROM ".DB_PREFIX."group_city where status =1 and verify = 1 order by pid desc"); //加入自动定位 foreach ($city_list as $city) { //if(@strpos($address['area1'],$city['name'])) if(strstr($address['area1'],$city['name'])!=false||strstr($city['name'],$address['area1'])!=false) { $city_sub = $GLOBALS['db']->getRow("SELECT id,name,py FROM ".DB_PREFIX."group_city where status =1 and verify= 1 and pid =".$city['id']." order by sort"); if ($city_sub){ $cityID = $city_sub['id']; }else{ $cityID = $city['id']; } break; } } } if($cityID > 0) $currentCity = $GLOBALS['db']->getRowCached("SELECT id,py FROM ".DB_PREFIX."group_city where id = $cityID and verify=1 and status =1"); if(empty($currentCity)) $currentCity = $GLOBALS['db']->getRowCached("SELECT id,py FROM ".DB_PREFIX."group_city where is_defalut=1 and verify=1 and status =1"); setcookie('cityID',base64_encode(serialize($currentCity['id']))); $_SESSION['cityID'] = $currentCity['id']; $_SESSION['cityName'] = $currentCity['py']; return $currentCity['id']; }
//获取当前城市跟客户端IPif(!isset($_SESSION['CLIENT_IP']) || empty($_SESSION['C_CITY_ID']) ||(isset($_REQUEST['cityname']) && !empty($_REQUEST['cityname']))){ require ROOT_PATH.'app/source/class/IpLocation.class.php'; define("C_CITY_ID",getCurrentCityID()); $_SESSION['C_CITY_ID'] = C_CITY_ID; $iplocation = new IpLocation(); $client_ip = $iplocation->getIP(); $_SESSION['CLIENT_IP'] = $client_ip; if(intval(a_fanweC("FIRST_VISIT_CITY"))==1&&isset($_REQUEST['cityname']) && !isset($_COOKIE['had_select_city'])){ setcookie('had_select_city',true,time()+365*60*60*24); }}
最后完成获取地址定位的操作。