2014-03-04 97 views
0

我有一個多語種站點,在example.com域上有一個'index.php'。這個index.php應該有這個重定向代碼,所以當用戶訪問'example.com'時,他們會被重定向到該網站的法文或英文版本。基於IP位置的PHP重定向

以最簡單的形式。我想在條件語句爲:

如果IP是總部設在法國重定向到example.com/fr否則,如果在世界其他地方重定向到example.com/en

我該如何使用PHP進行設置?

+0

你有IP位置的數據庫嗎? – user1844933

+0

@ user1844933不,我不知道。爲什麼這需要? – egr103

回答

0

看看http://www.geoplugin.com/webservices/php並使用緩存來存儲IP地址,因爲每次都不發出請求。

<?php 
error_reporting(-1); 
ini_set("display_errors", "On"); 

$ch = curl_init('http://www.geoplugin.net/php.gp?ip={the IP address, used mine for example}'); 

if (!$ch) { 
    die('Failed CURL'); 
} 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$serverResponse = curl_exec($ch); 

if (!$serverResponse) { 
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    throw new Exception('HTTP error: ' . $code); 
} 

die(print_r($serverResponse)); 

會導致:

Array 
(
    [geoplugin_request] => My IP 
    [geoplugin_status] => 206 
    [geoplugin_credit] => Some of the returned data includes GeoLite data created by MaxMind, available from <a href=\'http://www.maxmind.com\'>http://www.maxmind.com</a>. 
    [geoplugin_city] => 
    [geoplugin_region] => 
    [geoplugin_areaCode] => 0 
    [geoplugin_dmaCode] => 0 
    [geoplugin_countryCode] => GB 
    [geoplugin_countryName] => United Kingdom 
    [geoplugin_continentCode] => EU 
    [geoplugin_latitude] => 51.5 
    [geoplugin_longitude] => -0.13 
    [geoplugin_regionCode] => 
    [geoplugin_regionName] => 
    [geoplugin_currencyCode] => GBP 
    [geoplugin_currencySymbol] => &#163; 
    [geoplugin_currencySymbol_UTF8] => £ 
    [geoplugin_currencyConverter] => 0.6003 
) 

因此,使用國家代碼。