2012-09-18 78 views
0

讓我用一個例子解釋: -我可以獲取網站的位置嗎?

讓利說http://www.washingtontimes.com/news/2012/sep/18/pentagon-stops-training-partnering-afghan-troops-b/是提交了一個用戶的URL,現在我需要的是在PHP或方法的JavaScript或任何其他Web腳本語言,它可以給我與上面的url相對應的位置,就像這個網站在哪個國家/地區託管的那樣, 因爲在這種情況下結果應該是「美國」。它由許多網站完成,如http://www.site24x7.com,但我需要一個代碼來做到這一點

+0

那麼你有什麼嘗試?對你如何解決問題有任何初步的想法? –

+0

你可以從http://www.whoisxmlapi.com/這樣的WHOIS API獲得這個信息 - 他們不是免費的,但 – Timm

回答

0

你需要什麼內置到PHP中。使用gethostbyname方法查找IP地址,然後使用免費API查找位置(例如MaxMind) 也有PHP中的parse_url方法可幫助您從URL中獲取實際的域名。當有更安全的方法可用時,不要使用shell_exec。

1

你可以這樣做,從網址獲取主機名,然後使用gethostbyname()獲取IP,然後從whois網站獲取有關IP的一些信息。

<?php 
$url = 'http://www.washingtontimes.com/news/2012/sep/18/pentagon-stops-training-partnering-afghan-troops-b/'; 

$host = parse_url($url,PHP_URL_HOST); 
$ip = gethostbyname($host); 
$info = get_ip_info($ip); 

$result = array('host'=>$host, 'ip'=>$ip, 'info'=>$info); 

print_r($result); 
/* 
Array 
(
    [host] => www.washingtontimes.com 
    [ip] => 38.118.71.70 
    [info] => Array 
     (
      [host] => theconservatives.com 
      [country] => United States 
      [country_code] => USA 
      [continent] => North America 
      [region] => Virginia 
      [latitude] => 38.9687 
      [longitude] => -77.3411 
      [organization] => Cogent Communications 
      [isp] => Cogent Communications 
     ) 

) 
*/ 
echo $result['info']['country']; //United States 

function get_ip_info($ip = NULL){ 
    if(empty($ip)) $ip = $_SERVER['REMOTE_ADDR']; 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,'http://www.ipaddresslocation.org/ip-address-locator.php'); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch, CURLOPT_POST,true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS,array('ip'=>$ip)); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    preg_match_all('/<i>([a-z\s]+)\:<\/i>\s+<b>(.*)<\/b>/im',$data,$matches,PREG_SET_ORDER); 
    if(count($matches)==0)return false; 
    $return = array(); 
    $labels = array(
    'Hostname'   => 'host', 
    'IP Country'  => 'country', 
    'IP Country Code' => 'country_code', 
    'IP Continent'  => 'continent', 
    'IP Region'   => 'region', 
    'IP Latitude'  => 'latitude', 
    'IP Longitude'  => 'longitude', 
    'Organization'  => 'organization', 
    'ISP Provider'  => 'isp'); 
    foreach($matches as $info){ 
     if(isset($info[2]) && !is_null($labels[$info[1]])){ 
      $return[$labels[$info[1]]]=$info[2]; 
     } 
    } 

    return (count($return))?$return:false; 
} 
?> 
+0

男人你是上帝!!!!! – Manish

相關問題