search
HomeBackend DevelopmentPHP TutorialThinkPHP使用UTFWry地址库进行IP定位实例_php实例

可以在官网的 http://www.thinkphp.cn/extend/223.html下载IP定位扩展类库,或者下载扩展包( http://www.thinkphp.cn/down/253.html)里面也已经包含该扩展类了。如果是单独下载的上传类库,把解压后的IpLocation.class.php 放入ThinkPHP/Extend/Library/ORG/Net/(如果没有请手动创建)目录下面。

一、获取IP地址

如果你仅仅需要获取用户访问的IP地址,那么直接使用系统内置的get_client_ip函数即可,该函数是ThinkPHP标准模式内置方法,可以直接使用,比PHP内置的系统变量$_SERVER['HTTP_CLIENT_IP']具有更好的兼容性,用法:

复制代码 代码如下:
$ip = get_client_ip();

get_client_ip支持IP地址的多种情况检测和合法性验证,返回值就是获取到的IP地址,如果获取到的IP地址非法,将返回0.0.0.0。
如果需要,也可以返回IPV4地址数字,例如:

复制代码 代码如下:
$ip = get_client_ip(1);

返回的结果可能类似于:

复制代码 代码如下:
2130706433

可用于地址范围和比较。

二、IP地址定位
仅仅获取IP地址并不能完全满足应用的需求,只能记录下来用于日后的日志分析需要,IP地址定位功能可以让你获取用户的所在区域。要使用IP定位功能,除了需要IpLocation扩展类库之外,还需要IP地址库文件,由于ThinkPHP默认采用UTF8编码,因此最好是UTF8格式的IP地址库文件,如果是纯真gbk编码的IP地址库文件,则需要对获取结果进行编码转换(下面会提到),可以在这里下载UTF8编码的地址库文件: http://www.thinkphp.cn/extend/270.html
解压后的地址库文件UTFWry.dat放入IpLocation扩展类库所在目录下面即可。
使用方法:

复制代码 代码如下:
import('ORG.Net.IpLocation');// 导入IpLocation类
$Ip = new IpLocation(); // 实例化类
$location = $Ip->getlocation('218.79.93.194'); // 获取某个IP地址所在的位置

返回的location变量是一个数组,包括:

复制代码 代码如下:
$location['ip'] // IP地址
$location['beginip'] // 用户IP所在范围的开始地址
$location['endip'] // 用户IP所在范围的结束地址
$location['country'] // 所在国家或者地区
$location['area'] // 所在区域

通常,我们要获取IP定位的话,只需要取country和area信息:

复制代码 代码如下:
$info =  $location['country'].$location['area'];

如果你使用的IP地址库文件不是UTFWry.dat(注意在Linux下面文件名的大小写也需要一致)的话,我们需要在实例化IpLocation类的时候传入地址库文件名,例如:

复制代码 代码如下:
$Ip = new IpLocation('MyIpWry.dat'); // 传入IP地址库文件名

如果你的IP地址库是GBK编码的话,需要对返回结果进行编码转换。例如:

复制代码 代码如下:
$info = iconv('gbk','utf-8',$location['country'].$location['area']);

如果调用getlocation方法的时候没有传入任何参数,系统会自动调用上面的get_client_ip函数获取当前所在IP地址:

复制代码 代码如下:
$location = $Ip->getlocation();

也可以支持传入域名来自动获取ip地址

复制代码 代码如下:
import('ORG.Net.IpLocation');// 导入IpLocation类
$Ip = new IpLocation(); // 实例化类
$area = $Ip->getlocation('www.thinkphp.cn'); // 获取域名服务器所在的位置
dump($area);

运行结果输出:

ThinkPHP使用UTFWry地址库进行IP定位实例_php实例

如果大家使用的是纯真IP地址库,或者经常需要变换不同的地址库,为了方便IP定位的查询,也可以单独封装一个函数来获取位置信息,参考这里: http://www.thinkphp.cn/code/88.html

Statement
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

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 Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version