网站屏蔽指定省市 禁止IP查看网站

<?php 
    //屏蔽北上广
    $ip = get_client_ip();
    // $url = "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
    $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=".$ip;
    $data = https_request($url);
    $data = json_decode($data, true);

    $region = $data['province'];
    if($region == '广东' || $region == '北京' || $region == '上海'){
        header("Content-type: text/html; charset=utf-8");
        echo "<h1>网站升级中</h1>";
        die;
    }

    /**
     * 获取访客IP地址
     *
     * @param      integer  $type   The type
     * @param      boolean  $adv    The advance
     *
     * @return     array    The client ip.
     */
    function get_client_ip($type = 0,$adv=false) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos    =   array_search('unknown',$arr);
                if(false !== $pos) unset($arr[$pos]);
                $ip     =   trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip     =   $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip     =   $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    /**
     * 获取接口数据
     *
     * @param      <type>  $url    The url
     *
     * @return     <type>  ( description_of_the_return_value )
     */
    function https_request($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

Tags: 笔记

添加新评论