codeigniter源代码分析之输入类 Input.php

输入类主要是读取、处理客户端发送过来的http头信息

基本方法有:

get post cookie server 数据

获取header

设置cookie

获取(验证)ip

user_agent

识别请求模式 is_ajax_request is_cli_request

检测请求数据的 key val 是否有非法char

不安全的全局变量清除

源码注释:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CI_Input {
	var $ip_address				= FALSE;
	var $user_agent				= FALSE;
	var $_allow_get_array		= TRUE;
	var $_standardize_newlines	= TRUE;
	var $_enable_xss			= FALSE;
	var $_enable_csrf			= FALSE;
	protected $headers			= array();
	public function __construct()
	{
		log_message('debug', "Input Class Initialized");
		// 是否允许接收get数组 是否进行xss过滤 是否csrf保护
		$this->_allow_get_array	= (config_item('allow_get_array') === TRUE);
		$this->_enable_xss		= (config_item('global_xss_filtering') === TRUE);
		$this->_enable_csrf		= (config_item('csrf_protection') === TRUE);

		global $SEC;
		$this->security =& $SEC;
		if (UTF8_ENABLED === TRUE)
		{
			global $UNI;
			$this->uni =& $UNI;
		}
		$this->_sanitize_globals();
	}
	function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE)
	{
		// 请求的数据不存在
		if ( ! isset($array[$index]))
		{
			return FALSE;
		}

		if ($xss_clean === TRUE)
		{
			return $this->security->xss_clean($array[$index]);//xss过滤数据
		}

		return $array[$index];
	}
	// 返回 get 数组
	function get($index = NULL, $xss_clean = FALSE)
	{
		if ($index === NULL AND ! empty($_GET))
		{
			$get = array();
			foreach (array_keys($_GET) as $key)
			{
				$get[$key] = $this->_fetch_from_array($_GET, $key, $xss_clean);
			}
			return $get;
		}
		return $this->_fetch_from_array($_GET, $index, $xss_clean);
	}
	// 返回post数组
	function post($index = NULL, $xss_clean = FALSE)
	{
		if ($index === NULL AND ! empty($_POST))
		{
			$post = array();
			foreach (array_keys($_POST) as $key)
			{
				$post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean);
			}
			return $post;
		}

		return $this->_fetch_from_array($_POST, $index, $xss_clean);
	}
	function get_post($index = '', $xss_clean = FALSE)
	{
		if ( ! isset($_POST[$index]) )
		{
			return $this->get($index, $xss_clean);
		}
		else
		{
			return $this->post($index, $xss_clean);
		}
	}
	// 返回cookie数组
	function cookie($index = '', $xss_clean = FALSE)
	{
		return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
	}
	function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE)
	{
		if (is_array($name))
		{
			// always leave 'name' in last place, as the loop will break otherwise, due to $$item
			foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'name') as $item)
			{
				if (isset($name[$item]))
				{
					$$item = $name[$item];
				}
			}
		}

		if ($prefix == '' AND config_item('cookie_prefix') != '')
		{
			$prefix = config_item('cookie_prefix');
		}
		if ($domain == '' AND config_item('cookie_domain') != '')
		{
			$domain = config_item('cookie_domain');
		}
		if ($path == '/' AND config_item('cookie_path') != '/')
		{
			$path = config_item('cookie_path');
		}
		if ($secure == FALSE AND config_item('cookie_secure') != FALSE)
		{
			$secure = config_item('cookie_secure');
		}

		if ( ! is_numeric($expire))
		{
			$expire = time() - 86500;
		}
		else
		{
			$expire = ($expire > 0) ? time() + $expire : 0;
		}

		setcookie($prefix.$name, $value, $expire, $path, $domain, $secure);
	}
	// 返回SERVER全局数组 可以将index 进行 strtoupper()操作
	function server($index = '', $xss_clean = FALSE)
	{
		return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
	}
	// 获取ip地址 并且还要对ip进行识别 验证ip合法性
	public function ip_address()
	{
		if ($this->ip_address !== FALSE)
		{
			return $this->ip_address;//已经存在ip_address 返回数据
		}

		$proxy_ips = config_item('proxy_ips');
		if ( ! empty($proxy_ips))
		{//代理IP不空
			$proxy_ips = explode(',', str_replace(' ', '', $proxy_ips));
			foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP') as $header)
			{//遍历server中关于IP的信息
				if (($spoof = $this->server($header)) !== FALSE)
				{
					// Some proxies typically list the whole chain of IP
					// addresses through which the client has reached us.
					// e.g. client_ip, proxy_ip1, proxy_ip2, etc.
					if (strpos($spoof, ',') !== FALSE)
					{
						$spoof = explode(',', $spoof, 2);
						$spoof = $spoof[0]; //获取IP值 存入 spoof
					}

					if ( ! $this->valid_ip($spoof))
					{
						$spoof = FALSE;//过滤失败
					}
					else
					{
						break;//找到IP停止遍历
					}
				}
			}
			// spoof有值且存在与代理IP中 ip_address 赋值为 spoof 不然就用 REMOTE_ADDR
			$this->ip_address = ($spoof !== FALSE && in_array($_SERVER['REMOTE_ADDR'], $proxy_ips, TRUE))
				? $spoof : $_SERVER['REMOTE_ADDR'];
		}
		else
		{
			$this->ip_address = $_SERVER['REMOTE_ADDR'];
		}

		if ( ! $this->valid_ip($this->ip_address))
		{
			$this->ip_address = '0.0.0.0';//过滤IP失败设置默认值
		}

		return $this->ip_address;
	}
	public function valid_ip($ip, $which = '')
	{//过滤IP
		$which = strtolower($which);
		if (is_callable('filter_var'))
		{
			switch ($which) {
				case 'ipv4':
					$flag = FILTER_FLAG_IPV4;
					break;
				case 'ipv6':
					$flag = FILTER_FLAG_IPV6;
					break;
				default:
					$flag = '';
					break;
			}
			//尝试用php内置过滤函数
			return (bool) filter_var($ip, FILTER_VALIDATE_IP, $flag);
		}

		if ($which !== 'ipv6' && $which !== 'ipv4')
		{//通过ip格式 确定ip类型
			if (strpos($ip, ':') !== FALSE)
			{
				$which = 'ipv6';
			}
			elseif (strpos($ip, '.') !== FALSE)
			{
				$which = 'ipv4';
			}
			else
			{
				return FALSE;
			}
		}

		$func = '_valid_'.$which;
		return $this->$func($ip);
	}
	protected function _valid_ipv4($ip)
	{
		$ip_segments = explode('.', $ip);
		if (count($ip_segments) !== 4)
		{
			return FALSE;//v4 IP 4段
		}
		if ($ip_segments[0][0] == '0')//不能以0开始
		{
			return FALSE;
		}
		// 过滤并不严格
		foreach ($ip_segments as $segment)
		{
			if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
			{
				return FALSE;
			}
		}

		return TRUE;
	}
	protected function _valid_ipv6($str)
	{
		// 8 groups, separated by :
		// 0-ffff per group
		// one set of consecutive 0 groups can be collapsed to ::
		$groups = 8;
		$collapsed = FALSE;

		$chunks = array_filter(
			preg_split('/(:{1,2})/', $str, NULL, PREG_SPLIT_DELIM_CAPTURE)
		);

		// Rule out easy nonsense
		if (current($chunks) == ':' OR end($chunks) == ':')
		{
			return FALSE;
		}

		// PHP supports IPv4-mapped IPv6 addresses, so we'll expect those as well
		if (strpos(end($chunks), '.') !== FALSE)
		{
			$ipv4 = array_pop($chunks);

			if ( ! $this->_valid_ipv4($ipv4))
			{
				return FALSE;
			}

			$groups--;
		}

		while ($seg = array_pop($chunks))
		{
			if ($seg[0] == ':')
			{
				if (--$groups == 0)
				{
					return FALSE;	// too many groups
				}

				if (strlen($seg) > 2)
				{
					return FALSE;	// long separator
				}

				if ($seg == '::')
				{
					if ($collapsed)
					{
						return FALSE;	// multiple collapsed
					}

					$collapsed = TRUE;
				}
			}
			elseif (preg_match("/[^0-9a-f]/i", $seg) OR strlen($seg) > 4)
			{
				return FALSE; // invalid segment
			}
		}

		return $collapsed OR $groups == 1;
	}
	// 返回用户代理(浏览器)信息
	function user_agent()
	{
		if ($this->user_agent !== FALSE)
		{
			return $this->user_agent;
		}

		$this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT'];

		return $this->user_agent;
	}
	// 全局数组的处理
	function _sanitize_globals()
	{
		// It would be "wrong" to unset any of these GLOBALS.
		$protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST',
							'_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA',
							'system_folder', 'application_folder', 'BM', 'EXT',
							'CFG', 'URI', 'RTR', 'OUT', 'IN');

		// This is effectively the same as register_globals = off
		// 效果如同 register_globals=off 将全局变量中key出现在 protected数组中 将这个全局变量置空 赋值NULL
		foreach (array($_GET, $_POST, $_COOKIE) as $global)
		{
			if ( ! is_array($global))
			{
				if ( ! in_array($global, $protected))
				{
					global $$global;
					$$global = NULL;
				}
			}
			else
			{
				foreach ($global as $key => $val)
				{
					if ( ! in_array($key, $protected))
					{
						global $$key;
						$$key = NULL;
					}
				}
			}
		}
		// 禁用GET数组
		if ($this->_allow_get_array == FALSE)
		{
			$_GET = array();
		}
		else
		{
			if (is_array($_GET) AND count($_GET) > 0)
			{
				// 对数组的key val 安全检测
				foreach ($_GET as $key => $val)
				{
					$_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
				}
			}
		}
		if (is_array($_POST) AND count($_POST) > 0)
		{
			// 对数组的key val 安全检测
			foreach ($_POST as $key => $val)
			{
				$_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
			}
		}
		if (is_array($_COOKIE) AND count($_COOKIE) > 0)
		{
			// 没用CI提供的方法set cookie 进行如此处理
			// Also get rid of specially treated cookies that might be set by a server
			// or silly application, that are of no use to a CI application anyway
			// but that when present will trip our 'Disallowed Key Characters' alarm
			// http://www.ietf.org/rfc/rfc2109.txt
			// note that the key names below are single quoted strings, and are not PHP variables
			unset($_COOKIE['$Version']);
			unset($_COOKIE['$Path']);
			unset($_COOKIE['$Domain']);

			foreach ($_COOKIE as $key => $val)
			{
				$_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
			}
		}

		// 去除 html xml php 的标签
		$_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);
		if ($this->_enable_csrf == TRUE && ! $this->is_cli_request())
		{//设置了csrf 且不是命令行的input进行验证verify
			$this->security->csrf_verify();
		}

		log_message('debug', "Global POST and COOKIE data sanitized");
	}
	function _clean_input_data($str)
	{
		if (is_array($str))
		{
			$new_array = array();
			foreach ($str as $key => $val)
			{
				$new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
			}
			return $new_array;
		}
		// get_magic_quotes_gpc() 检测是否开启 magic_quotes 这个会对 get post cookie 数据进行自动转义
		if ( ! is_php('5.4') && get_magic_quotes_gpc())
		{
			// 转义字符
			$str = stripslashes($str);
		}
		if (UTF8_ENABLED === TRUE)
		{
			$str = $this->uni->clean_string($str);
		}
		// 去除不可显示的字符
		$str = remove_invisible_characters($str);
		if ($this->_enable_xss === TRUE)
		{//xss过滤
			$str = $this->security->xss_clean($str);
		}
		// PHP_EOL php根据不同运行环境(系统)设置换行符
		if ($this->_standardize_newlines == TRUE)
		{
			if (strpos($str, "\r") !== FALSE)
			{
				$str = str_replace(array("\r\n", "\r", "\r\n\n"), PHP_EOL, $str);
			}
		}

		return $str;
	}
	// 检测get post 数组的key是否合法
	function _clean_input_keys($str)
	{
		if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
		{
			exit('Disallowed Key Characters.');
		}
		// 进行utf8转码
		if (UTF8_ENABLED === TRUE)
		{
			$str = $this->uni->clean_string($str);
		}

		return $str;
	}
	// 解析出http请求头信息
	public function request_headers($xss_clean = FALSE)
	{
		if (function_exists('apache_request_headers'))
		{//直接从apache获取头部信息
			$headers = apache_request_headers();
		}
		else
		{
			$headers['Content-Type'] = (isset($_SERVER['CONTENT_TYPE'])) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE');
			foreach ($_SERVER as $key => $val)
			{//过滤server数组中HTTP_开头的信息 添加到数组
				if (strncmp($key, 'HTTP_', 5) === 0)
				{
					$headers[substr($key, 5)] = $this->_fetch_from_array($_SERVER, $key, $xss_clean);
				}
			}
		}
		foreach ($headers as $key => $val)
		{
			// 将header数组中的key替换成 Content-Type 的形式 并赋值回去
			$key = str_replace('_', ' ', strtolower($key));
			$key = str_replace(' ', '-', ucwords($key));
			$this->headers[$key] = $val;
		}

		return $this->headers;
	}
	// 取得http请求头信息
	public function get_request_header($index, $xss_clean = FALSE)
	{
		if (empty($this->headers))
		{
			$this->request_headers(); //this->header 数组为空 调用方法 request_headers 获取头请求数据
		}

		if ( ! isset($this->headers[$index]))
		{
			return FALSE; //请求的头信息不存在
		}

		if ($xss_clean === TRUE)
		{
			return $this->security->xss_clean($this->headers[$index]);//对数据进行xss过滤
		}
		return $this->headers[$index];
	}
	// 请求是否为ajax
	public function is_ajax_request()
	{
		return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest');
	}
	// 请求是否是CLI
	public function is_cli_request()
	{
		return (php_sapi_name() === 'cli' OR defined('STDIN'));
	}

}

Code Tips:

各种过滤实现得学习

ip过滤、key val过滤

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值