PHP get a text tutorial on guest (client) IP and geolocation

Source: Internet
Author: User
Tags fread unpack
In the daily development process we often need to analyze the behavior of client users, then record these behaviors must be to obtain the client's real IP information, this chapter tutorial, we will explain how to get the client: language, browser, operating system, IP, geographical location, ISP and other information.

First we need to download the PHP class library used in this Charter tutorial http://www.php.cn/xiazai/leiku/827

The class used to be Baidu's IP library, due to the failure of Baidu's IP library, I modified the class, using the local IP library, if you also need to use the local IP library then go to download: UTFWry.dat Baidu Search under a lot, you can the latest.

Instantiate the class:

$obj = new Class_guest_info;     echo $obj->getlang (). ' <br/> ';        Get the language of your visitors: Simplified Chinese, Traditional Chinese, 中文版.     echo  $obj->getbrowser (). ' <br/> ';     Get the Guest browser: MSIE, Firefox, Chrome, Safari, Opera, other.     echo  $obj->getos (). ' <br/> ';          Get guest OS: Windows, MAC, Linux, Unix, BSD, other.   echo   $obj->getip (). ' <br/> ';          Gets the guest IP address.    $ipinfo =  $obj->getadd ();         Get the visitor's location and use Baidu to hide the interface. echo $ipinfo [' Country ']. $ipinfo [' area '];

I will modify the class to upload to our PHP Chinese Web server address is http://www.php.cn/ip/ip.php

The following PHP classes handle the Pure IP library UTFWry.dat:

<?php/** * IP geolocation query class modified from coolcode.cn * Due to the use of UTF8 encoding if you use a pure IP address library, you need to encode the returned results * @category org * @package org * @s Ubpackage Net * @author liu21st <liu21st@gmail.com> */class iplocation {/** * QQWry.Dat file pointer * *    @var Resource */private $fp;    /** * The offset address of the first IP record * * @var int */private $firstip;    /** * The offset address of the last IP record * * @var int */private $lastip;    /** * Total number of entries for IP records (not including version information Records) * * @var int */private $totalip; /** * constructor, open QQWry.Dat file and initialize information in class * * @param string $filename * @return Iplocation */public func        tion __construct ($filename = "UTFWry.dat") {$this-&GT;FP = 0; if ($this-&GT;FP = fopen (dirname (__file__).            /'. $filename, ' RB ')!== false) {$this->firstip = $this->getlong ();            $this->lastip = $this->getlong ();        $this->totalip = ($this->lastip-$this->firstip)/7; }}/** * returnNumber of long integers read back * * @access private * @return int */Private Function Getlong () {//Little-endian encoding to be read        4 bytes into a long integer $result = unpack (' Vlong ', fread ($this-&GT;FP, 4));    return $result [' Long '];        }/** * Returns the number of Read 3-byte long integers * * @access private * @return int */Private Function getlong3 () {        Converts the Read Little-endian encoded 3 bytes to a long integer $result = unpack (' Vlong ', fread ($this-&GT;FP, 3). chr (0));    return $result [' Long ']; /** * Returns the compressed IP address that can be compared * * @access private * @param string $ip * @return String */Private function Packip ($IP) {//IP address is converted to a long integer, if the IP address is incorrect in PHP5, return false,///Then Intval convert flase to integer-1, then compress to Big-endian encoded    String return pack (' N ', Intval (Ip2long ($IP))); }/** * Returns the Read String * * @access private * @param string $data * @return String */Private Funct        Ion GetString ($data = "") {$char = Fread ($this->fp, 1); while (Ord ($char) >0) {//string is saved in C format to end $data. = $char;        Connect prompt the read word to the given string $char = Fread ($this->fp, 1);    } return $data;  }/** * Returns region information * * @access private * @return String */Private Function Getarea () {$byte    = Fread ($this->fp, 1);                Flag byte switch (ORD ($byte)) {case 0://no region information $area = "";            Break Case 1:case 2://The flag byte is 1 or 2, indicating that the zone information is redirected fseek ($this->fp, $this->getlong                3 ());                $area = $this->getstring ();            Break                Default://Otherwise, indicates that the zone information is not redirected $area = $this->getstring ($byte);        Break    } return $area; /** * Returns the region information according to the given IP address or domain name * * @access public * @param string $IP * @return Array */Publ IC function getlocation ($ip = ") {if (! $this-&GT;FP) return null;        If the data file is not opened correctly, the empty if (empty ($IP)) $ip = Get_client_ip () is returned directly;   $location [' ip '] = gethostbyname ($IP);   Convert the entered domain name to an IP address $ip = $this->packip ($location [' IP ']);        Converting the IP address you enter into a comparable IP address//an illegal IP address is converted to 255.255.255.255//Sub-search                         $l = 0;            Bottom boundary $u of search = $this->totalip;        Top boundary of search $findip = $this->lastip; If not found, returns the last IP record (version information for QQWry.Dat) while ($l <= $u) {//when the upper boundary is less than the lower boundary, the lookup fails $i = Floor (($  L + $u)/2);            Calculate approximate intermediate records fseek ($this->fp, $this->firstip + $i * 7);     $beginip = Strrev (fread ($this-&GT;FP, 4));            Get the start IP address of the intermediate record//The Strrev function here is to convert the Little-endian's compressed IP address into a Big-endian format//For comparison, and later the same.            if ($ip < $beginip) {//user's IP is less than the start IP address of the intermediate record $u = $i-1;  Modifies the top boundary of the search to an intermediate record minus one} else {              Fseek ($this->fp, $this->getlong3 ());   $endip = Strrev (fread ($this-&GT;FP, 4));        Gets the end IP address of the intermediate record if ($ip > $endip) {//The IP of the user is greater than the end IP address of the intermediate record $l = $i + 1; Modify the bottom boundary of the search to an intermediate record plus one} else {//The IP of the user is within the IP range of the intermediate record $findi                    p = $this->firstip + $i * 7;              Break        To find the result, exit the Loop}}}//Get the IP geolocation information found fseek ($this->fp, $findip);   $location [' beginip '] = Long2ip ($this->getlong ());        The start address of the range where the user IP is located $offset = $this->getlong3 ();        Fseek ($this->fp, $offset);     $location [' endip '] = Long2ip ($this->getlong ());    End address of the range where the user IP is located $byte = fread ($this->fp, 1); The flag byte switch (ORD ($byte)) {Case 1://Flag Byte is 1, indicating that both country and region information are redirected at the same time $cou         Ntryoffset = $this->getlong3 ();      REDIRECT Address          Fseek ($this->fp, $countryOffset);    $byte = Fread ($this->fp, 1);                        Flag byte switch (ORD ($byte)) {Case 2://Flag Byte is 2, indicating that country information is redirected again                        Fseek ($this->fp, $this->getlong3 ());                        $location [' country '] = $this->getstring ();                        Fseek ($this->fp, $countryOffset + 4);                        $location [' area '] = $this->getarea ();                    Break                        Default://Otherwise, indicates that the country information is not redirected $location [' country '] = $this->getstring ($byte);                        $location [' area '] = $this->getarea ();                Break            } break;                Case 2://The flag byte is 2, indicating that the country information is redirected fseek ($this->fp, $this->getlong3 ());                $location [' country '] = $this->getstring ();            Fseek ($this->fp, $offset + 8);    $location [' area '] = $this->getarea ();            Break                Default://Otherwise, indicates that the country information is not redirected $location [' country '] = $this->getstring ($byte);                $location [' area '] = $this->getarea ();        Break } if ($location [' country '] = = "php.cn") {//CZ88.        NET means no valid information $location [' country '] = "Unknown";        if ($location [' area '] = = "php.cn") {$location [' area '] = "";    } return $location;     The/** * destructor is used to automatically close open files after the page execution ends.        * */Public Function __destruct () {if ($this->fp) {fclose ($this-&GT;FP);    } $this->fp = 0; }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.