如何在 PHP 中根据国家/地区的 IP 地址重定向域名?

phpserver side programmingprogramming更新于 2025/6/27 14:22:17

GeoIP 扩展可用于查找 IP 地址的确切位置。除此之外,geoPlugin 类可以从以下链接下载 − 。

http://www.geoplugin.com/_media/webservices/geoplugin.class.phps

国家代码列表可在以下链接中找到 −

http://www.geoplugin.com/iso3166

可以在根文件夹中放置一个 index.php 文件,并将以下代码行放入此索引文件中 −

<?php
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
// 为地区代码创建一个变量
$var_country_code = $geoplugin->countryCode;
// 根据地区代码重定向:
if ($var_country_code == &"AL") {
   header('Location: http://sq.wikipedia.org/');
}
else if ($var_country_code == &"NL") {
   header('Location: http://nl.wikipedia.org/');
} else {
   header('Location: http://en.wikipedia.org/');
}
?>

下载 geoplugin 类后,将创建一个新实例并将其命名为 ‘geoplugin’。在 geoplugin 类的此实例上调用 locate 函数。同一类对象的 countryCode 被赋值给名为 ‘var_country_code’ 的变量。现在,设置 ‘if’ 条件来检查区域的字母。基于此 IP 地址,将重定向到特定域名。


相关文章