Home > Backend Development > PHP Tutorial > PHP implements method to obtain client IP and obtain IP information

PHP implements method to obtain client IP and obtain IP information

墨辰丷
Release: 2023-03-31 18:54:01
Original
1338 people have browsed it

This article mainly introduces the example of how to obtain the client IP and obtain the IP information in PHP. It is very practical. Friends in need can come and refer to it.

The code is very concise and the function is very practical. I won’t go into too much nonsense here. I will just give it to you:

The code is as follows:

<?php
/**
 * 获取客户端IP
 * @param  integer $type 返回类型 0:string,1:long
 * @return string|long
 */
function getClientIp($type = 0) {
    $ip = NULL;
    if (isset($_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;])) {
        $arr = explode(&#39;,&#39;, $_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;]);
        $pos = array_search(&#39;unknown&#39;,$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip  = trim($arr[0]);
    }elseif (isset($_SERVER[&#39;HTTP_CLIENT_IP&#39;])) {
        $ip = $_SERVER[&#39;HTTP_CLIENT_IP&#39;];
    }elseif (isset($_SERVER[&#39;REMOTE_ADDR&#39;])) {
        $ip = $_SERVER[&#39;REMOTE_ADDR&#39;];
    }
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array(&#39;0.0.0.0&#39;, 0);
    return $ip[$type];
}
/**
 * 获取IP信息
 * @param  string|long $ip  IP地址
 * @return array
 */
function getIpInfo($ip)
{
    if (is_long($ip)) {
        $ip = long2ip($ip);
    }
    $api = &#39;http://ip.taobao.com/service/getIpInfo.php&#39;;
    $ret = file_get_contents($api . &#39;?ip=&#39; . $ip);
    $ret = json_decode($ret, true);
    if ($ret[&#39;code&#39;] == 0) {
        return $ret[&#39;data&#39;];
    } 
    return array();
}
Copy after login

Summary: Above That’s the entire content of this article, I hope it will be helpful to everyone’s study.

Related recommendations:

How to generate a reference implementation tree in PHP

##PHP uses phpmailer to send emails

Definition and use of magic methods in PHP

The above is the detailed content of PHP implements method to obtain client IP and obtain IP information. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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