CI框架源码完全分析之核心文件(输入类)Input.php

CodeIgniter的输入类Input.php确实很强大:过滤超级全局变量的键名和键值;摧毁外部全局变量;可配置不允许$_GET数组;可配置开启全局XSS和CSRF等等。
CodeIgniter的输入类Input.php提供了很多有用的方法,并在helper中封装了函数:
$this->input->get() //获取$_GET

$this->input->post() //获取$_POST

$this->input->get_post() //获取$_GET或$_POST

$this->input->cookie() //获取$_COOKIE

$this->input->set_cookie() //设置COOKIE

$this->input->server() //获取$_SERVER

$this->input->ip_address() //获取ip地址

$this->input->valid_ip($ip) //验证ip地址

$this->input->user_agent() //获取浏览器user_agent

$this->input->request_headers() //获取request_headers

$this->input->get_request_header(); //获取request_headers中的一项信息

$this->input->is_ajax_request() //判断是否是ajax请求

/**
 * Input Class
 * 
 * @link http://www.phpddt.com
 */
class CI_Input {

    /**
     *当前用户的ip地址
     */
    var $ip_address                = FALSE;
    /**
     * 当前用户的浏览器user_agent信息
     */
    var $user_agent                = FALSE;
    /**
     * 是否允许获取$_GET超级全局变量
     */
    var $_allow_get_array      = TRUE;
    /**
     * 设置标准换行
     */
    var $_standardize_newlines = TRUE;
    /**
     * 是否开启全局的xss过滤
     */
    var $_enable_xss           = FALSE;
    /**
     * 是否开启CSRF过滤
     */
    var $_enable_csrf          = FALSE;
    /**
     * 记录http request信息
     */
    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();
    }

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

    /**
     * 从$array数组中取得某个key的值,并可设置是否进行xss过滤
     */
    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值,并可进行xss过滤
        * 可以看出获取不指定key也可以进行过滤:$this->input->get(NULL, TRUE); 
    */
    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中指定item,和get()原理一样
    */
    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);
    }


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

    /**
     * 可同时获取$_GET值或$_POST值
         */
    function get_post($index = '', $xss_clean = FALSE)
    {
        if ( ! isset($_POST[$index]) )
        {
            return $this->get($index, $xss_clean);
        }
        else
        {
            return $this->post($index, $xss_clean);
        }
    }

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

    /**
    * 获取HTTP Cookies超级全局变量$_COOKIE的值
    */
    function cookie($index = '', $xss_clean = FALSE)
    {
        return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
    }

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

    /**
     * 设置cookie
         * @param $name  可作为数组形式传入所有参数
         * @param $value  设置cookie的值
         * @param $expire 设置cookie的有效时间
         * @param $domain 设置cookie的有效域名
         * @param $path 设置cookie的有效路径
         * @param $prefix 设置cookie前缀
         * @param $secure 设置是否在安全的HTTPS传输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');
        }
                //是否配置cookie有效域名
        if ($domain == '' AND config_item('cookie_domain') != '')
        {
            $domain = config_item('cookie_domain');
        }
                //是否配置cookie的有效路径,默认是当前目录
        if ($path == '/' AND config_item('cookie_path') != '/')
        {
            $path = config_item('cookie_path');
        }
                //规定是否通过安全的 HTTPS 连接来传输 cookie。
        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($prefix.$name, $value, $expire, $path, $domain, $secure);
    }

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

    /**
    * 获取超级全局变量$_SERVER的值
    */
    function server($index = '', $xss_clean = FALSE)
    {
        return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
    }

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

    /**
    * Fetch the IP Address
    *
    * @return   string
    */
    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;
    }

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

    /**
    * Validate IPv6 Address
    */
    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;
        }

        // IPv4映像地址
        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信息
    */
    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;
    }

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

    /**
    * 过滤全局变量,保护功能如下:
    *
    * 当配置allow_get_array为FALSE,则Unsets $_GET
    *
    * 当开启register_globals,Unsets all globals,以防安全
    *
    * Standardizes newline characters to \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是否开启注册全局变量,相当于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;
                    }
                }
            }
                        die;
        }

        // 如果在config中配置allow_get_array为FALSE,那么$_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);
                }
            }
        }

        // 过滤$_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);
            }
        }

        // 过滤$_COOKIE值
        if (is_array($_COOKIE) AND count($_COOKIE) > 0)
        {
            // 这里过滤一些可能被服务器特殊处理的cookie
            // 注意下面的键名是单引号,不是php变量
            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);
            }
        }

        // 过滤PHP_SELF
        $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);


        // 如果开启csrf保护
        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);
        }

        // 彼岸准换行,不同的操作系统换行不同,unix系列用 /n,windows系列用 /r/n,mac用 /r,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;
    }

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

    /**
    * 过滤键值
    */
    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;
    }

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

    /**
     * 获取http 请求头信息
     */
    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;
    }

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

    /**
     * 获取http 头信息,如果设置xxs_clean了则过滤
     */
    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'));
    }

}

转载注明地址: http://www.phpddt.com/php/php-input-class.html 尊重他人劳动成果就是尊重自己!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值