最近在作關於方維的項目,方維的根據ip定位思路大概是這樣的,在路由分發控制器前載入了一個叫作user_init.php的文件,查看這我的第一次訪問時cookie裏面和url裏面是否有關於城市的記錄,若是沒有的話,自動跳到城市選擇頁,php
//首次訪問跳轉到城市選擇 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裏。cookie
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']; }
//獲取當前城市跟客戶端IP if(!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); } }
最後完成獲取地址定位的操做。session