duanhua5523 2013-09-19 13:07
浏览 54
已采纳

使用php检查IP地址

I am writing a thumb up/down rating system on items, The rating system should allow the user to rate only one time. I have an SQL table in the database named rating with columns : id, itemname, commentno. and another table ip_check that has : id, commentno, ip.

The commentno will be a foreign key and the syntax to get the ip should be like this : <?php $ip = $_SERVER['REMOTE_ADDR']; ?> as I checked on line on several links like this one.

Now what is the proper and easiest way to add a mysql if condition. I checked this link as well but I am still looking for something more specific, any help on this?

  • 写回答

1条回答 默认 最新

  • duanbo19834 2013-09-19 13:29
    关注

    For saving and in Mysql I recommended use Mysql function INET_NTOA() and INET_ATON()

    For validating and get IP address I using this functions:

    function is_ip($ip) {
        global $localIPs;
        $test = 0;
        $pattern='/^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/';
        $ip = explode(',', $ip);
        $ip = array_map('trim', $ip);
        foreach ($ip as $key => $value) {
            if(array_search($value, $localIPs)===false && preg_match($pattern, $value)) $test = $value;
        }
        if(!empty($test)) return $test;
        else return false;
    }
    
    function get_ip() {
        $ip='';
        if(!empty($_SERVER['HTTP_X_REAL_IP']) && is_ip($_SERVER['HTTP_X_REAL_IP'])) $ip=is_ip($_SERVER['HTTP_X_REAL_IP']);
        elseif(!empty($_SERVER['HTTP_CLIENT_IP']) && is_ip($_SERVER['HTTP_CLIENT_IP'])) $ip=is_ip($_SERVER['HTTP_CLIENT_IP']);
        elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip=is_ip($_SERVER['HTTP_X_FORWARDED_FOR']);
        else $ip=is_ip($_SERVER['REMOTE_ADDR']);
        return $ip;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)