Use an IP address to determine which city the user is accessing the PHP code
- Function detect_city ($ ip ){
-
- $ Default = 'unknown ';
-
- $ Curlopt_useragent = 'mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: 1.9.2) Gecko/20100115 Firefox/3.6 (. net clr 3.5.30729 )';
-
- $ Url = 'http: // ipinfodb.com/ip_locator.php? Ip = '. urlencode ($ ip );
- $ Ch = curl_init ();
-
- $ Curl_opt = array (
- CURLOPT_FOLLOWLOCATION => 1,
- CURLOPT_HEADER => 0,
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_USERAGENT => $ curlopt_useragent,
- CURLOPT_URL => $ url,
- CURLOPT_TIMEOUT => 1,
- CURLOPT_REFERER => 'http: // '. $ _ SERVER ['http _ host'],
- );
-
- Curl_setopt_array ($ ch, $ curl_opt );
-
- $ Content = curl_exec ($ ch );
-
- If (! Is_null ($ curl_info )){
- $ Curl_info = curl_getinfo ($ ch );
- }
-
- Curl_close ($ ch );
-
- If (preg_match ('{
- City: ([^ <] *)
} I ', $ content, $ regs )){
- $ City = $ regs [1];
- }
- If (preg_match ('{
- State/Province: ([^ <] *)
} I ', $ content, $ regs )){
- $ State = $ regs [1];
- }
-
- If ($ city! = ''& $ State! = ''){
- $ Location = $ city. ','. $ state;
- Return $ location;
- } Else {
- Return $ default;
- }
-
- }
Usage:
- $ Ip = $ _ SERVER ['remote _ ADDR '];
- $ City = detect_city ($ ip );
- Echo $ city;
- ?>
|
Which city is it in?