class CI_Input {
//用户ip地址
protected $ip_address = FALSE;
//用户浏览器地址
protected $user_agent = FALSE;
//允许get方式提交数据
protected $_allow_get_array = TRUE;
//新行央视标记
protected $_standardize_newlines = TRUE;
//xss攻击过滤
protected $_enable_xss = FALSE;
//csrf攻击过滤
protected $_enable_csrf = FALSE;
//http请求头
protected $headers = array(); //构造函数
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();
} //从数组取出数据
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];
} //从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
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)
{
// 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);
} //从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);
}
} //从COOKIE中取出数据
function cookie($index = '', $xss_clean = FALSE)
{
return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
} //设置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];
}
}
} 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数组中取出数据
function server($index = '', $xss_clean = FALSE)
{
return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
} //获取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;
} //验证IP地址
public function valid_ip($ip, $which = '')
{
$which = strtolower($which); // First check if filter_var is available
if (is_callable('filter_var'))
{
switch ($which) {
case 'ipv4':
$flag = FILTER_FLAG_IPV4;
break;
case 'ipv6':
$flag = FILTER_FLAG_IPV6;
break;
default:
$flag = '';
break;
} 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);
} //验证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;
} //验证IPv6地址
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'); // Unset globals for securiy.
// This is effectively the same as 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
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
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
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
$_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");
} //净化输入数据
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;
} //净化输入数据键名
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;
} //设置请求头信息
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;
} //获取请求头
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];
} //是否是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'));
} }

CI框架 -- 核心文件 之 Input.php(输入数据处理文件)的更多相关文章

  1. CI框架 -- 核心文件 之 Hooks.php

    钩子 - 扩展框架核心 CodeIgniter 的钩子特性提供了一种方法来修改框架的内部运作流程,而无需修改 核心文件.CodeIgniter 的运行遵循着一个特定的流程,你可以参考这个页面的 应用程 ...

  2. CI框架 -- 核心文件 之 Loader.php(加载器)

    顾名思义,装载器就是加载元素的,使用CI时,经常加载的有: 加载类库文件:$this->load->library()   加载视图文件:$this->load->view() ...

  3. CI框架 -- 核心文件 之 Exceptions.php

    使用CI框架,我们通常使用一下三个函数处理错误: show_error('消息' [, int $status_code = 500 ] ) show_404('页面' [, 'log_error'] ...

  4. CI框架 -- 核心文件 之 Common.php

    system/core/Common.php 文件中可以定义 公共函数,我们可以在这里定义自己的公共函数.在任何情况下你都能够使用这些函数.使用他们不需要载入任何类库或辅助函数. 接下来分析下该文件中 ...

  5. CI框架 -- 核心文件 之 config.php

    Config:该文件包含CI_Config类,这个类包含启用配置文件来管理的方法 /** * 加载配置文件 * * @param string $file 配置文件名 * @param bool $u ...

  6. CI框架 -- 核心文件 之 Output.php(输出类文件)

    CI输出类Output.php的功能是将最终web页面发送给浏览器,这里面的东西可能是你用的最少的.你使用装载器加载了一个视图文件, 这个视图文件的内容会自动传递给输出类对象, 然后呢,在方法执行完毕 ...

  7. CI框架 -- 核心文件 之 Benchmark.php

    Benchmark.php文件中定义的CI_Benchmark类可以让你标记点,并计算它们之间的时间差.还可以显示内存消耗. Benchmarking类库,它是被系统自动被加载的,不需要手工加载 cl ...

  8. CI框架 -- 核心文件 之 Model.php

    class CI_Model { /** * Class constructor * * @return void */ public function __construct() { log_mes ...

  9. CI框架 -- 核心文件 之 Lang.php(加载语言包)

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class CI_Lang { var $l ...

随机推荐

  1. 对于iOS开发人工智能意味着什么

    对于iOS开发人工智能意味着什么? 前言 近几年来人工智能的话题那是炙手可热.在国内很多大佬言必谈机器学习和大数据:在美国刚毕业的人工智能 PHD 也是众人追捧,工资直逼 NFL 四分卫.人工智能甚至 ...

  2. FFmpeg Basics学习笔记(1)ffmpeg基础

    1 FFmpeg的由来 FFmpeg缩写中,FF指的是Fast Forward,mpeg是 Moving Pictures Experts Group的缩写.官网:ffmpeg.org 编译好的可执行 ...

  3. kvm libvirt 虚拟机管理

    http://www.2cto.com/os/201203/123128.html kvm虚拟机管理一.环境role         hostname    ip                  O ...

  4. poj1733(区间上的种类并查集)

    题目大意是:一个由0,1组成的数字串~~,现在你问一个人,第i位到第j位的1的个数为奇数还是偶数.一共会告诉你几组这样的数 要你判断前k组这个人回答的都是正确的,到第k+1组,这个人说的是错的,要你输 ...

  5. Gridview排序与分页-不使用“DataSourceControl DataSource”的情况下如何分页和排序 ...

    如果你在GridView控件上设置 AllowPaging="true" or AllowSorting="true" 而没有使用使用数据源控件 DataSou ...

  6. JAVA-数据库之Statement对象

    相关资料:<21天学通Java Web开发> 语句对象Statement1.语句对象Statement可以用来执行SQL语句,从而实现数据库操作.2.可以通过调用连接对象的createSt ...

  7. java---简单的ATM存取系统,

    新手练手必备~ 密码账户为: 先创建账户类: package cn.Atm; /** * @author 偶my耶 */ import java.io.*; import com.project.pr ...

  8. [转]Oracle中Hint深入理解

    原文地址:http://czmmiao.iteye.com/blog/1478465 Hint概述 基于代价的优化器是很聪明的,在绝大多数情况下它会选择正确的优化器,减轻了DBA的负担.但有时它也聪明 ...

  9. poj3436 ACM Computer Factory, 最大流,输出路径

    POJ 3436 ACM Computer Factory 电脑公司生产电脑有N个机器.每一个机器单位时间产量为Qi. 电脑由P个部件组成,每一个机器工作时仅仅能把有某些部件的半成品电脑(或什么都没有 ...

  10. android App抓包工具的应用(转)

    安装好 fiddler ,手头有一部Android 手机,同时 还要有无线网,手机和 电脑在同一个无线网络.这些条件具备,我们就可以 开始下面的步骤了. 正题 :Fiddler 主菜单 Tools - ...