Parse PHP to query the region based on IP (very useful, used by Ganji.com)_PHP tutorial

WBOY
Release: 2016-07-21 15:01:58
Original
855 people have browsed it

dat file, information file about the region corresponding to the IP
qqwry.dat file
Download it online

class file, parse the qqwry.data file
IpLocation.php file

Copy code The code is as follows:

class IpLocation {
    /**
* @var resource pointer
*/
    private $fp;
    /**
* Offset address of the first IP record
* @var int
*/
    private $firstip;
    /**
* Offset address of the last IP record
* @var int
*/
    private $lastip;
    /**
* The total number of IP records (excluding version information records)
* @var int
*/
    private $totalip;
    /**
* Constructor, open the QQWry.Dat file and initialize the information in the class
* @param string $filename
* @return IpLocation
*/
    public function __construct($filename = "qqwry.dat") {
        $this->fp = 0;
        if (($this->fp = @fopen($filename, 'rb')) !== false) {
            $this->firstip = $this->getlong();
            $this->lastip = $this->getlong();
            $this->totalip = ($this->lastip - $this->firstip) / 7;
        }
    }
    /**
* Return the read long integer
* @access private
* @return int
*/
    public function getlong() {
        //将读取的little-endian编码的4个字节转化为长整型数
        $result = unpack('Vlong', fread($this->fp, 4));
        return $result['long'];
    }
    /**
* Return the read 3-byte long integer
*
* @access private
* @return int
*/
    public function getlong3() {
        //将读取的little-endian编码的3个字节转化为长整型数
        $result = unpack('Vlong', fread($this->fp, 3).chr(0));
        return $result['long'];
    }
    /**
* Returns the IP address that can be compared after compression
*
* @access private
* @param string $ip
* @return string
*/
    public function packip($ip) {
        // 将IP地址转化为长整型数,如果在PHP5中,IP地址错误,则返回False,
        // 这时intval将Flase转化为整数-1,之后压缩成big-endian编码的字符串
        return pack('N', intval(ip2long($ip)));
    }
    /**
* Return the read string
*
* @access private
* @param string $data
* @return string
*/
    public function getstring($data = "") {
        $char = fread($this->fp, 1);
        while (ord($char) > 0) { // 字符串按照C格式保存,以
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!