现在的位置: 首页 > 综合 > 正文

CodeIgniter core/input.php

2013年10月12日 ⁄ 综合 ⁄ 共 15820字 ⁄ 字号 评论关闭

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package CodeIgniter
 * @author ExpressionEngine Dev Team
 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
 * @license http://codeigniter.com/user_guide/license.html
 * @link http://codeigniter.com
 * @since Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Input Class
 *
 * Pre-processes global input data for security
 *
 * @package CodeIgniter
 * @subpackage Libraries
 * @category Input
 * @author ExpressionEngine Dev Team
 * @link http://codeigniter.com/user_guide/libraries/input.html
 */
class CI_Input {

/**
* IP address of the current user
*
* @var string
*/
//当前用户的ip地址
var $ip_address
= FALSE;
/**
* user agent (web browser) being used by the current user
*
* @var string
*/
//用户当前使用的 浏览器的用户代理
var $user_agent
= FALSE;
/**
* If FALSE, then $_GET will be set to an empty array
*
* @var bool
*/
//如果设为FALSE,则销毁全局GET数组
var $_allow_get_array
= TRUE;
/**
* If TRUE, then newlines are standardized
*
* @var bool
*/
//如果为TRUE,使用标准的换行符
var $_standardize_newlines
= TRUE;
/**
* Determines whether the XSS filter is always active when GET, POST or COOKIE data is encountered
* Set automatically based on config setting
*
* @var bool
*/
//为TRUE,则阻止通过GET,POST,COOKIE的跨站脚本攻击
var $_enable_xss
= FALSE;
/**
* Enables a CSRF cookie token to be set.
* Set automatically based on config setting
*
* @var bool
*/
//csrf:跨站请求伪造
var $_enable_csrf
= FALSE;
/**
* List of all HTTP request headers
*
* @var array
*/
//http的头信息
protected $headers
= array();

/**
* Constructor
*
* Sets whether to globally enable the XSS processing
* and whether to allow the $_GET array
*
* @return
void
*/
public function __construct()
{
log_message('debug', "Input Class Initialized");
//初始化变量

$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;
// Do we need the UTF-8 class?

if (UTF8_ENABLED === TRUE)
{
global $UNI;
$this->uni =& $UNI;
}

// Sanitize global arrays
$this->_sanitize_globals();
}

// --------------------------------------------------------------------

/**
* Fetch from array
*
* This is a helper function to retrieve values from global arrays
*
* @access
private
* @param
array
* @param
string
* @param
bool
* @return
string
*/
//从全全局数组中检索某个索引值
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]);
}

return $array[$index];
}

// --------------------------------------------------------------------

/**
* Fetch an item from the GET array
*
* @access
public
* @param
string
* @param
bool
* @return
string
*/
//从GET数组中得到某个值
function get($index = NULL, $xss_clean = FALSE)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_GET))
{
$get = array();

// loop through the full _GET array
//array_keys — 返回数组中所有的键名

//取出所有的GET值

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);
}

// --------------------------------------------------------------------

/**
* Fetch an item from the POST array
*
* @access
public
* @param
string
* @param
bool
* @return
string
*/
//如果数据不存在,方法将返回 FALSE (布尔值)。
//第二个参数是可选的,如果想让取得的数据经过跨站脚本过滤(XSS Filtering),把第二个参数设为TRUE。
//不设置任何参数,该方法将以一个数组的形式返回全部POST过来的数据。
//把第一个参数设置为NULL,第二个参数设置为 TRUE (boolean),该方法将经过跨站脚本过滤,返回一个包含全部POST数据的数组。
//如果POST没有传递任何数据,该方法将返回 FALSE (boolean)
function post($index = NULL, $xss_clean = FALSE)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_POST))
{
$post = array();

// Loop through the full _POST array and return it
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);
}

// --------------------------------------------------------------------

/**
* Fetch an item from either the GET array or the POST
*
* @access
public
* @param
string The index key
* @param
bool XSS cleaning
* @return
string
*/
//这个方法将会搜索POST和GET方式的数据流,首先以POST方式搜索,然后以GET方式搜索:
function get_post($index = '', $xss_clean = FALSE)
{
if ( ! isset($_POST[$index]) )
{
return $this->get($index, $xss_clean);
}
else
{
return $this->post($index, $xss_clean);
}
}

// --------------------------------------------------------------------

/**
* Fetch an item from the COOKIE array
*
* @access
public
* @param
string
* @param
bool
* @return
string
*/
//此方法类似post方法,用来取得cookie数据:
function cookie($index = '', $xss_clean = FALSE)
{
return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
}

// ------------------------------------------------------------------------

/**
* Set cookie
*
* Accepts six parameter, or you can submit an associative
* array in the first parameter containing all the values.
*
* @access
public
* @param
mixed
* @param
string the value of the cookie
* @param
string the number of seconds until expiration
* @param
string the cookie domain.  Usually:  .yourdomain.com
* @param
string the cookie path
* @param
string the cookie prefix
* @param
bool true makes the cookie secure
* @return
void
*/
//设置一个 Cookie 的值。这个函数接收两种形式的参数:数组形式和参数形式:
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];
}
}
}

//得到cookie参数值
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');
}

//设置cookie的有效期
if ( ! is_numeric($expire))
{
$expire = time() - 86500;
}
else
{
$expire = ($expire > 0) ? time() + $expire : 0;
}
/*setcookie() 函数向客户端发送一个 HTTP cookie。
*cookie 是由服务器发送到浏览器的变量。cookie 通常是服务器嵌入到用户计算机中的小文本文件。
*每当计算机通过浏览器请求一个页面,就会发送这个 cookie。
*cookie 的名称指定为相同名称的变量。例如,如果被发送的 cookie 名为 "name",会自动创建名为 $user 的变量,
*包含 cookie 的值。必须在任何其他输出发送前对 cookie 进行赋值。
*如果成功,则该函数返回 true,否则返回 false。
*/
setcookie($prefix.$name, $value, $expire, $path, $domain, $secure);
}

// --------------------------------------------------------------------

/**
* Fetch an item from the SERVER array
*
* @access
public
* @param
string
* @param
bool
* @return
string
*/
//此方法类似上面两个方法,用来取得server数据:
function server($index = '', $xss_clean = FALSE)
{
return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
}

// --------------------------------------------------------------------

/**
* Fetch the IP Address
*
* @return
string
*/
//返回当前用户的IP。如果IP地址无效,返回0.0.0.0的IP:
public function ip_address()
{
if ($this->ip_address !== FALSE)
{
return $this->ip_address;
}

$proxy_ips = config_item('proxy_ips');
//代理处理
if ( ! empty($proxy_ips))
{
$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)
{
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];
}

if ( ! $this->valid_ip($spoof))
{
$spoof = FALSE;
}
else
{
break;
}
}
}

$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';
}

return $this->ip_address;
}

// --------------------------------------------------------------------

/**
* Validate IP Address
*
* @access
public
* @param
string
* @param
string ipv4 or ipv6
* @return
bool
*/
//测试输入的IP地址是不是有效,返回布尔值TRUE或者FALSE。 
//注意:$this->input->ip_address()自动测试输入的IP地址本身格式是不是有效。
public function valid_ip($ip, $which = '')
{
$which = strtolower($which);

// First check if filter_var is available
//is_callable 检测参数是否为合法的可调用结构

if (is_callable('filter_var'))
{
switch ($which) {
case 'ipv4':
$flag = FILTER_FLAG_IPV4;
break;
case 'ipv6':
$flag = FILTER_FLAG_IPV6;
break;
default:
$flag = '';
break;
}
//filter_var — Filters a variable with a specified filter
return (bool) filter_var($ip, FILTER_VALIDATE_IP, $flag);
}

if ($which !== 'ipv6' && $which !== 'ipv4')
{
if (strpos($ip, ':') !== FALSE)
{
$which = 'ipv6';
}
elseif (strpos($ip, '.') !== FALSE)
{
$which = 'ipv4';
}
else
{
return FALSE;
}
}

$func = '_valid_'.$which;
return $this->$func($ip);
}

// --------------------------------------------------------------------

/**
* Validate IPv4 Address
*
* Updated version suggested by Geert De Deckere
*
* @access
protected
* @param
string
* @return
bool
*/
//ipv4地址验证
protected function _valid_ipv4($ip)
{
$ip_segments = explode('.', $ip);

// Always 4 segments needed
if (count($ip_segments) !== 4)
{
return FALSE;
}
// IP can not start with 0
if ($ip_segments[0][0] == '0')
{
return FALSE;
}

// Check each segment
foreach ($ip_segments as $segment)
{
// IP segments must be digits and can not be
// longer than 3 digits or greater then 255
if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
{
return FALSE;
}
}

return TRUE;
}

// --------------------------------------------------------------------

/**
* Validate IPv6 Address
*
* @access
protected
* @param
string
* @return
bool
*/
//ipv4地址验证
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;
}

// --------------------------------------------------------------------

/**
* User Agent
*
* @access
public
* @return
string
*/
//返回当前用户正在使用的浏览器的user agent信息。 如果不能得到数据,返回FALSE。
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;
}

// --------------------------------------------------------------------

/**
* Sanitize Globals
*
* This function does the following:
*
* Unsets $_GET data (if query strings are not enabled)
*
* Unsets all globals if register_globals is enabled
*
* Standardizes newline characters to \n
*
* @access
private
* @return
void
*/
//审查全局变量
//1、如果enable_query_string设为FALSE,则删除$_GET数组
//2、如果register_globals设为On,则删除所有的全局变量
//设置标准的换行符为:"\n"
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');

// Unset globals for securiy.
// This is effectively the same as register_globals = off
//安全的删除全局变量。此方法与register_globals = off是等同的
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;
}
}
}
}

// Is $_GET data allowed? If not we'll set the $_GET to an empty array
//清空$_GET数组
if ($this->_allow_get_array == FALSE)
{
$_GET = array();
}
else
{
if (is_array($_GET) AND count($_GET) > 0)
{
foreach ($_GET as $key => $val)
{
$_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
}
}
}

// Clean $_POST Data
//清空$_POST数组
if (is_array($_POST) AND count($_POST) > 0)
{
foreach ($_POST as $key => $val)
{
$_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
}
}

// Clean $_COOKIE Data
//清空COOKIE数据
if (is_array($_COOKIE) AND count($_COOKIE) > 0)
{
// 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);
}
}
//检测脚本的文件名
// Sanitize PHP_SELF
//strip_tags — 从字符串中去除 HTML 和 PHP 标记

$_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);

// CSRF Protection check on HTTP requests
if ($this->_enable_csrf == TRUE && ! $this->is_cli_request())
{
$this->security->csrf_verify();
}

log_message('debug', "Global POST and COOKIE data sanitized");
}

// --------------------------------------------------------------------

/**
* Clean Input Data
*
* This is a helper function. It escapes data and
* standardizes newline characters to \n
*
* @access
private
* @param
string
* @return
string
*/
//处理输入的数据
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;
}

/* We strip slashes if magic quotes is on to keep things consistent

  NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and
it will probably not exist in future versions at all.
*/
if ( ! is_php('5.4') && get_magic_quotes_gpc())
{
$str = stripslashes($str);
}

// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE)
{
$str = $this->uni->clean_string($str);
}

// Remove control characters
$str = remove_invisible_characters($str);

// Should we filter the input data?
if ($this->_enable_xss === TRUE)
{
$str = $this->security->xss_clean($str);
}

// Standardize newlines if needed
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;
}

// --------------------------------------------------------------------

/**
* Clean Keys
*
* This is a helper function. To prevent malicious users
* from trying to exploit keys we make sure that keys are
* only named with alpha-numeric text and a few other items.
*
* @access
private
* @param
string
* @return
string
*/
//处理输入的key

function _clean_input_keys($str)
{
if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
{
exit('Disallowed Key Characters.');
}

// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE)
{
$str = $this->uni->clean_string($str);
}

return $str;
}

// --------------------------------------------------------------------

/**
* Request Headers
*
* In Apache, you can simply call apache_request_headers(), however for
* people running other webservers the function is undefined.
*
* @param
bool XSS cleaning
*
* @return array
*/
//在不支持apache_request_headers()的非Apache环境非常有用。返回请求头(header)数组。
public function request_headers($xss_clean = FALSE)
{
// Look at Apache go!
if (function_exists('apache_request_headers'))
{
$headers = apache_request_headers();
}
else
{
$headers['Content-Type'] = (isset($_SERVER['CONTENT_TYPE'])) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE');

foreach ($_SERVER as $key => $val)
{
if (strncmp($key, 'HTTP_', 5) === 0)
{
$headers[substr($key, 5)] = $this->_fetch_from_array($_SERVER, $key, $xss_clean);
}
}
}

// take SOME_HEADER and turn it into Some-Header
foreach ($headers as $key => $val)
{
$key = str_replace('_', ' ', strtolower($key));
$key = str_replace(' ', '-', ucwords($key));

$this->headers[$key] = $val;
}

return $this->headers;
}

// --------------------------------------------------------------------

/**
* Get Request Header
*
* Returns the value of a single member of the headers class member
*
* @param string
array key for $this->headers
* @param
boolean XSS Clean or not
* @return mixed
FALSE on failure, string on success
*/
//返回请求头(request header)数组中某一个元素的值
public function get_request_header($index, $xss_clean = FALSE)
{
if (empty($this->headers))
{
$this->request_headers();
}

if ( ! isset($this->headers[$index]))
{
return FALSE;
}

if ($xss_clean === TRUE)
{
return $this->security->xss_clean($this->headers[$index]);
}

return $this->headers[$index];
}

// --------------------------------------------------------------------

/**
* Is ajax Request?
*
* Test to see if a request contains the HTTP_X_REQUESTED_WITH header
*
* @return boolean
*/
//检查服务器头HTTP_X_REQUESTED_WITH是否被设置,并返回布尔值。
public function is_ajax_request()
{
return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest');
}

// --------------------------------------------------------------------

/**
* Is cli Request?
*
* Test to see if a request was made from the command line
*
* @return bool
*/
//检查看常量STDIN是否被设置, 这只是一个检查PHP是否以命令行方式运行的应急方法。
public function is_cli_request()
{
return (php_sapi_name() === 'cli' OR defined('STDIN'));
}

}

/* End of file Input.php */
/* Location: ./system/core/Input.php */

抱歉!评论已关闭.