• PHP通过访问第三方接口,根据IP地址获取所在城市


    <?php
    header('Content-Type:text/html;Charset=utf-8');
    
    /**
     * 获取IP地址
     *
     * @return string
     */
    function get_ip() {
    	$realip = '';
    	$unknown = 'unknown';
    	if (isset($_SERVER)) {
    		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
    			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    			foreach ($arr as $ip) {
    				$ip = trim($ip);
    				if ($ip != 'unknown') {
    					$realip = $ip;
    					break;
    				}
    			}
    		} else if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)) {
    			$realip = $_SERVER['HTTP_CLIENT_IP'];
    		} else if (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
    			$realip = $_SERVER['REMOTE_ADDR'];
    		} else {
    			$realip = $unknown;
    		}
    	} else {
    		if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)) {
    			$realip = getenv("HTTP_X_FORWARDED_FOR");
    		} else if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)) {
    			$realip = getenv("HTTP_CLIENT_IP");
    		} else if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)) {
    			$realip = getenv("REMOTE_ADDR");
    		} else {
    			$realip = $unknown;
    		}
    	}
    	$realip = preg_match("/[d.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;
    	return $realip;
    }
    
    /**
     * 根据IP获取地址详情
     *
     * @param string $ip
     * @return bool|mixed
     */
    function get_ip_info($ip = '') {
    	if (empty($ip)) {
    		$ip = get_ip();
    	}
    
    	$res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    	if (empty($res)) {
    		return false;
    	}
    
    	$jsonMatches = array();
    	preg_match('#{.+?}#', $res, $jsonMatches);
    	if (!isset($jsonMatches[0])) {
    		return false;
    	}
    	
    	$json = json_decode($jsonMatches[0], true);
    	if (isset($json['ret']) && $json['ret'] == 1) {
    		$json['ip'] = $ip;
    		unset($json['ret']);
    	} else {
    		return false;
    	}
    	
    	return $json;
    }
    
    $ipInfos = get_ip_info('123.125.114.144'); // baidu.com IP地址
    print_r($ipInfos);

    输出:

     

    特别说明

    使用 file_get_contents() 函数一定要加个超时时间设置,否则,网络差的时候会拖垮php-fpm进程!

    参考:

    http://blog.csdn.net/liruxing1715/article/details/28238483

  • 相关阅读:
    内存、时间复杂度、CPU/GPU以及运行时间
    内存、时间复杂度、CPU/GPU以及运行时间
    四叉树问题
    四叉树问题
    基于深度学习的人脸识别系统(Caffe+OpenCV+Dlib)【三】VGG网络进行特征提取
    爬楼梯问题种种
    爬楼梯问题种种
    Python 在线笔试
    基于深度学习的人脸识别系统(Caffe+OpenCV+Dlib)【二】人脸预处理
    标准模板库 STL 使用之 —— vector 使用 tricks
  • 原文地址:https://www.cnblogs.com/52php/p/5889800.html
Copyright © 2020-2023  润新知