Home Backend Development PHP Tutorial 在WordPress中使用PHP脚本来判断访客来自什么国家_PHP

在WordPress中使用PHP脚本来判断访客来自什么国家_PHP

May 28, 2016 pm 01:13 PM
php wordpress area visitor

区分访客国家有什么用?

这里是几个我利用该功能的例子.

1.区分网站功能
这个博客有翻译文章的功能, 这是为了方便海外访客阅读文章, 但对中国人显得十分多余. 所以我通过 IP 判断国家, 对中国大陆地区屏蔽翻译功能.

2.区分展示广告
比如中国大陆地区在侧边栏最下方看到的是拿福能的广告, 而其他地区看到的是 Google 的广告. hostucan 是我的一个广告主, 有英文网站, 也有中文网站, 所以我可以向他提供区分展示服务, 免得浪费流量.

3.屏蔽布点服务
海外有很多好的服务平台, 在网站上布点即可采集数据和分享文章. 但很不幸, 因为某些原因, 他们在国内展示效果并不好, 不但没有起到应有效果, 还让页面加载时间变长. 可以对大陆访客屏蔽这些布点.

在 PHP 通过 IP 区分国家

如何用 PHP 通过 IP 区分国家和地区呢? Maxmind.com 提供一套 GeoIP 的解决方案, 只需要简单几步即可在 PHP 中通过 IP 判断访客的国家.

1. 下载数据库和 PHP 库文件

下载 GeoID.dat.gz, 解压为 GeoIP.dat 文件.
下载 geoip.inc.
2. 通过 PHP 代码获取国家信息
以下是一段示范代码, 演示如何获取国家代号和国家名称.

<&#63;php
 
// 引入 PHP 库文件
include("geoip.inc");
 
// 打开本地数据库, 数据保存在 GeoIP 文件中.
$geoData = geoip_open('GeoIP.dat', GEOIP_STANDARD);
 
// 获取国家 IP
$countryCode = geoip_country_code_by_addr($geoData, $_SERVER['REMOTE_ADDR']);
 
// 获取国家名称
$countryName = geoip_country_name_by_addr($geoData, $_SERVER['REMOTE_ADDR']);
 
// 关闭本地数据库
geoip_close($geoData);
 
&#63;>
Copy after login

在 WordPress 中通过 IP 区分国家

既然 PHP 上使用没问题, WordPress 肯定也是 Okay 的. 看看我是怎么使用的.

1. 放置数据库文件
将 GeoIP.dat 解压到 WordPress 根目录中. (你可以在这个目录找到 wp-config.php 或者 wp-config-sample.php 文件)

2. 编写调用接口
在主题目录中新建文件夹 include, 将 geoip.inc 放置在新建文件夹中. 并在该文件夹新建文件 geoip.php 文件内容如下.

<&#63;php
 
include('geoip.inc');
 
global $countryCode;
 
$geoData = geoip_open('GeoIP.dat', GEOIP_STANDARD);
$countryCode = geoip_country_code_by_addr($geoData, $_SERVER['REMOTE_ADDR']);
geoip_close($geoData);
 
&#63;>
Copy after login

这里只取国家代号作为判别依据. 并且国家代号是全局变量, 以避免页面多处判断需要反复访问 GeoIP.dat 获取信息, 减少程序开销.

2. 调用接口, 获取国家代号
3. 打开 header.php 文件, 在文件顶部加入代码如下.

<&#63;php include('include/geoip.php'); &#63;>
Copy after login

4. 使用国家代号
在主题中调用代码, 例子如下.

<&#63;php
 
global $countryCode;
 
if($countryCode == 'CN') {
 // 中国大陆地区执行的代码
} else if($countryCode == 'US') {
 // 美国地区执行的代码
} else {
 // 中国大陆和美国以外地区执行的代码
}
 
&#63;>

Copy after login


可能有人会问, 加这么个东西, 性能如何? 会不会要求强大的服务器? 我测试过, 正常的服务器上几乎不影响页面加载性能, 可以看看这个博客的速度. 如果不放心, 自己测一下.

PS:采用IP查询API接口
国内不少互联网公司例如腾讯、新浪以及淘宝都有IP查询接口,直接调用查询即可。

(1)腾讯IP分享计划

代码如下:


/**根据腾讯IP分享计划的地址获取IP所在地,比较精确*/function getIPLoc_QQ($ip1){$url = 'http://ip.qq.com/cgi-bin/searchip?searchip1='.$ip1;$ch = curl_init($url);curl_setopt($ch,CURLOPT_ENCODING ,'gb2312');curl_setopt($ch, CURLOPT_TIMEOUT, 10);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回$result = curl_exec($ch);$result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换,否则乱码curl_close($ch);preg_match("@(.*)

@iU",$result,$ipArray);$loc = $ipArray[1];return $loc;}

(2)新浪IP查询接口

代码如下:


/**根据新浪IP查询接口获取IP所在地*/function getIPLoc_sina($ip1){$url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip='.$ip1;$ch = curl_init($url);//curl_setopt($ch,CURLOPT_ENCODING ,'utf8');curl_setopt($ch, CURLOPT_TIMEOUT, 10);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回$location = curl_exec($ch);$location = json_decode($location);curl_close($ch); $loc = "";if($location===FALSE) return "";if (emptyempty($location->desc)) {$loc = $location->province.$location->city.$location->district.$location->isp;}else{$loc = $location->desc;}return $loc;}

(3)使用淘宝IP接口

代码如下:


/** * 根据淘宝IP查询接口获取IP所在地 */function getCity($ip){$url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;$ip=json_decode(file_get_contents($url));if((string)$ip->code=='1'){ return false; } $data = (array)$ip->data;return $data;}


总结

通过 IP 判断访客来源十分精准的, 现在一些外贸网站都是通过这个方法向用户进行展示区分, 比如美国地区的用户默认看到美国能买到的商品和美国物流信息. 但不是百分之百的准确, 比如某人常年翻墙, 那他可能一直看不到本国的信息. 至于是否需要区分处理, 网站主要有所考虑.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

How to change the head image of the wordpress theme How to change the head image of the wordpress theme Apr 20, 2025 am 10:00 AM

A step-by-step guide to replacing a header image of WordPress: Log in to the WordPress dashboard and navigate to Appearance &gt;Theme. Select the topic you want to edit and click Customize. Open the Theme Options panel and look for the Site Header or Header Image options. Click the Select Image button and upload a new head image. Crop the image and click Save and Crop. Click the Save and Publish button to update the changes.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

How to view the front-end of WordPress How to view the front-end of WordPress Apr 20, 2025 am 10:30 AM

You can view the WordPress front-end by logging into the dashboard and switching to the View Sites tab; automate the viewing process with a headless browser; installing the WordPress plugin to preview the front-end within the dashboard; viewing the front-end via a local URL (if WordPress is set locally).

How to import the source code of wordpress How to import the source code of wordpress Apr 20, 2025 am 11:24 AM

Importing WordPress source code requires the following steps: Create a sub-theme for theme modification. Import the source code and overwrite the files in the sub-topic. Activate the sub-theme to make it effective. Test the changes to make sure everything works.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How to cancel the editing date of wordpress How to cancel the editing date of wordpress Apr 20, 2025 am 10:54 AM

WordPress editing dates can be canceled in three ways: 1. Install the Enable Post Date Disable plug-in; 2. Add code in the functions.php file; 3. Manually edit the post_modified column in the wp_posts table.

See all articles