Home > Backend Development > PHP Tutorial > Share the method of obtaining access IP in php

Share the method of obtaining access IP in php

小云云
Release: 2023-03-20 12:50:01
Original
2692 people have browsed it

This article mainly shares with you several methods of obtaining access IP in PHP, hoping to help everyone.

<?php                                                                 //方法1:
//方法4:
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    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;];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array(&#39;0.0.0.0&#39;, 0);
    return $ip[$type];
}
echo get_client_ip();
Copy after login

Related recommendations:

php Determine access IP

php method to determine access IP_PHP tutorial

5 ways for PHP to obtain user access IP address, ip5

The above is the detailed content of Share the method of obtaining access IP in php. 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