2012-12-30 30 views
0

我正在嘗試將用戶重定向到相應的國家/地區的PHP頁面。例如。美國 - mysite.com,澳大利亞 - mysite.com.au。我已通過此功能獲得IP地址,並希望使用此網站獲取其國家/地區:http://api.hostip.info/country.php?ip=在PHP中通過國家重定向用戶

if (getenv(HTTP_X_FORWARDED_FOR)) { 
    $ip_address = getenv(HTTP_X_FORWARDED_FOR); 
    echo $ip_address; 
} else { 
    $ip_address = getenv(REMOTE_ADDR); 
    echo $ip_address; 
} 

ip_address_to_number($ip_address); 
+0

與其說你可能想看看API的使用到[GeoIP的(http://php.net/manual/en/book.geoip.php) – PhearOfRayne

回答

2

我會建議使用NetImpact's API,但是您能特別告訴我們問題是什麼嗎?你所做的只是告訴我們你想要做什麼,但是你從未告訴我們你當前的代碼是如何發生故障的。

注意:Netimpact已關閉。他們已將用戶遷移到KickFire,其中有更廣泛的API產品:IP2GEO,IP2Company,Domain2IP。

但是,如果您只想獲取該網址的內容,那就很容易了。只要把這個在你的PHP頁面:

<?php 
$ip = $_SERVER['REMOTE_ADDR']; 
$url = 'http://api.hostip.info/country.php?ip=' . $ip; 
$country = file_get_contents($url); 
// Do something with the country, I am forwarding to a subdomain here but you can 
// do whatever you like. 
header('Location: http://' . $country. '.mysite.com'); 
?> 
+0

謝謝。我已經成功地獲取工作,但它給錯誤:無法修改重定向頁面時標題信息:如果($國家==「US」) \t \t { \t \t \t頭('位置:http:/ /mysite.com'); \t \t} \t \t \t \t否則,如果($國家== 'AU') \t \t { \t \t \t頭( '位置:http://mysite.com.au'); \t \t} – liamp47

+0

您必須在標題之前有輸出。如果你不想改變任何現有的代碼,只需緩衝輸出。把它放在頁面頂部之前:ob_start(); – SISYN