天天看点

根据ip地址获取相关区域信息

<?php
/**
 * 基于淘宝的ipAPI 根据ip地址 返回所在地
 * @author L.D.B
 * 2012/09/12
 */
header("Content-type:text/html; charset=utf-8");
$ip='61.183.248.38';
$url='http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
var_dump(curl_rpc($url));

/**
 * file_get_contents 获取信息
 * @param  $url
 */
function get_area_file($url){
	if(empty($url)){
		return false;
	}
	$file=file_get_contents($url);
	return json_decode($file,true);
}


function curl_rpc($url, $request='', $limit = 0, $timeout = 1){
		if (!$url)
			die('url is null');
		$urlarr = parse_url($url);
		$host = $urlarr['host'];
		$path = $urlarr['path'];
		$port = !empty($urlarr['port']) ? $urlarr['port'] : 80;
	
		$len = strlen($request);
		$hander = "POST $path HTTP/1.1\r\n";
		$hander .= "Host: $host:$port\r\n";
		$hander .= "Content-type: application/json\r\n";
		$hander .= "Connection: Close\r\n";
		$hander .= "Content-Length: $len\r\n";
		$hander .= "\r\n";
		$hander .= $request . "\r\n";
		$handerarr[0] = $hander;
	
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url); //The URL to fetch.
		curl_setopt($ch, CURLOPT_HEADER, 0); //TRUE to include the header in the output.
		curl_setopt($ch, CURLOPT_HTTPHEADER, $handerarr); //An array of HTTP header fields to set.
		curl_setopt($ch, CURLOPT_POST, 1); //TRUE to do a regular HTTP POST
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //TRUE to return the raw output
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); //The maximum number of seconds to allow CURL functions to execute.
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
}



/**
 * 获取当前ip地址
 */
function get_ip(){
	if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$ip = getenv('HTTP_CLIENT_IP');
	} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$ip = getenv('REMOTE_ADDR');
	} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
}