Core File (Input class) Input. php

Source: Internet
Author: User
CodeIgniter Input class Input. php is really powerful: it filters out key and key values of Super global variables; destroys external global variables; it can be configured to not allow $ _ GET arrays; it can be configured to enable global XSS and CSRF, and so on. CodeIgniter input

CodeIgniter Input class Input. php is really powerful: it filters out key and key values of Super global variables; destroys external global variables; it can be configured to not allow $ _ GET arrays; it can be configured to enable global XSS and CSRF, and so on.
CodeIgniter Input class Input. php provides many useful methods and encapsulates functions in helper:
$ This-> input-> get () // GET $ _ get
$ This-> input-> post () // Get $ _ POST
$ This-> input-> get_post () // GET $ _ GET or $ _ POST
$ This-> input-> cookie () // Get $ _ COOKIE
$ This-> input-> set_cookie () // sets the COOKIE
$ This-> input-> server () // Get $ _ SERVER
$ This-> input-> ip_address () // obtain the IP address
$ This-> input-> valid_ip ($ ip) // verify the ip address
$ This-> input-> user_agent () // Obtain the browser user_agent
$ This-> input-> request_headers () // Obtain request_headers
$ This-> input-> get_request_header (); // Obtain information in request_headers.
$ This-> input-> is_ajax_request () // determines whether the request is an ajax request.
 

/*** Input Class *** @ link http://www.phpddt.com */Class CI_Input {/*** IP address of the current user */var $ ip_address = FALSE;/*** user_agent information of the current user's browser */var $ user_agent = FALSE; /*** whether to allow obtaining the $ _ GET super global variable */var $ _ allow_get_array = TRUE;/*** set the standard line feed */var $ _ standardize_newlines = TRUE; /*** whether to enable global xss filtering */var $ _ enable_xss = FALSE;/*** whether to enable CSRF filtering */var $ _ enable_csrf = FALSE; /*** record http request information */protected $ headers = array ();/*** constructor */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 ();} // keys/*** get a key value from the $ array and set whether to perform xss filtering */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];} // ----------------------------------------------------------------------/*** obtain the $ _ GET value and perform xss filtering. * You can see that the obtained key can also be filtered: $ this-> input-> get (NULL, TRUE); */function get ($ index = NULL, $ xss_clean = FALSE) {// Check if a field has been providedif ($ index = null and! Empty ($ _ GET) {$ get = array (); // loop through the full _ GET arrayforeach (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);} // get/*** GET the specified item, and get () in $ _ POST () same principle */function post ($ index = NULL, $ xss_clean = FALSE) {// Check I F a field has been providedif ($ index = null and! Empty ($ _ POST) {$ post = array (); // Loop through the full _ POST array and return itforeach (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 $ _ GET value or $ _ POST value */function get_post ($ index = '', $ xss_clean = FALSE) {if (! Isset ($ _ POST [$ index]) {return $ this-> get ($ index, $ xss_clean);} else {return $ this-> post ($ index, $ xss_clean) ;}}// response/*** get the http cookie Super global variable $ _ cookie value */function COOKIE ($ index = '', $ xss_clean = FALSE) {return $ this-> _ fetch_from_array ($ _ COOKIE, $ index, $ xss_clean );}//-------------------------------------------------------------------- ----/*** Set cookie ** @ param $ name all parameters can be input as an array * @ param $ value set cookie value * @ param $ expire set cookie validity period *@ param $ domain: Set the valid domain name of the cookie * @ param $ path set the valid path of the cookie * @ param $ prefix set the cookie prefix * @ param $ secure set whether the cookie is valid for secure HTTPS transmission */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 $ itemforeach (array ('value', 'expire ', 'domain', 'path', 'prefix ', 'Secure ', 'name') as $ item) {if (isset ($ name [$ item]) {$ item = $ name [$ item] ;}} // Configure the cookie prefix if ($ prefix = ''AND config_item ('cookie _ prefix ')! = '') {$ Prefix = config_item ('cookie _ prefix ');} // whether to configure a valid cookie domain name if ($ domain = ''AND config_item ('cookie _ domain ')! = '') {$ Domain = config_item ('cookie _ domain ');} // whether to configure a valid cookie path, the default value is the current directory if ($ path = '/' AND config_item ('cookie _ path ')! = '/') {$ Path = config_item ('cookie _ path');} // specifies whether to transmit cookies through secure HTTPS connections. If ($ secure = false and config_item ('cookie _ secure ')! = FALSE) {$ secure = config_item ('cookie _ secure ');} // Set the cookie expiration time. default value: when the session ends, [close the browser] becomes invalid if (! Is_numeric ($ expire) {$ expire = time ()-86500;} else {$ expire = ($ expire> 0 )? Time () + $ expire: 0;} setcookie ($ prefix. $ name, $ value, $ expire, $ path, $ domain, $ secure );} // ----------------------------------------------------------------------/*** obtain the value of the Super global variable $ _ SERVER */function server ($ index = '', $ xss_clean = FALSE) {return $ this-> _ fetch_from_array ($ _ SERVER, $ index, $ xss_clean);} // returns/*** Fetch the IP Address ** @ re Turnstring */public function ip_address () {if ($ this-> ip_address! = FALSE) {return $ this-> ip_address;} $ proxy_ips = config_item ('proxy _ IP'); 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;} // token/*** verify the ip address */public function valid_ip ($ ip, $ which = '') {$ which = strtolower ($ which); // First check if filter_var is availableif (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);} // token/*** verify IPv4 address */protected function _ valid_ipv4 ($ ip) {$ ip_segments = explode ('. ', $ ip); // Always 4 segments neededif (count ($ ip_segments )! = 4) {return FALSE;} // IP can not start with 0if ($ ip_segments [0] [0] = '0') {return FALSE ;} // Check each segmentforeach ($ ip_segments as $ segment) {// IP segments must be digits and can not be // longer than 3 digits or greater then 255if ($ 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: // 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 nonsenseif (current ($ chunks) =': 'OR end ($ chunks) = ':') {return FALSE;} // IPv4 Image address 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 then 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} retu Rn $ collapsed OR $ groups = 1;} // returns the user agent information of the browser currently in use */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;} // filters global variables. the protection function is as follows: ** when allow_get_array is set to FALSE, Unsets $ _ GET ** when register_globals and Unsets all globals are enabled to prevent security ** Standardizes newline characters to \ n */function _ sanitize_globals () {// It wocould 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 refreshing tively the same as register_globals = off // whether register_globals enables registration of global variables, equivalent to register_globals = offforeach (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 ;}// if allow_get_array is set to FALSE in config, then $ _ GET is set to null 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) ;}}// filter the $ _ POST value if (is_array ($ _ POST) AND count ($ _ POST)> 0) {foreach ($ _ POST as $ key = >$ Val) {$ _ POST [$ this-> _ clean_input_keys ($ key)] = $ this-> _ clean_input_data ($ val );}} // filter $ _ COOKIE value if (is_array ($ _ COOKIE) AND count ($ _ COOKIE)> 0) {// filter some cookies that may be specially processed by the server. // note that the following key names are single quotes, not the php variable 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) ;}// filter PHP_SELF $ _ SE RVER ['php _ SELF '] = strip_tags ($ _ SERVER ['php _ SELF']); // if csrf protection is enabled, if ($ this-> _ enable_csrf = TRUE &&! $ This-> is_cli_request () {$ this-> security-> csrf_verify ();} log_message ('debug', "Global POST and COOKIE data sanitized ");} // outputs/*** filter input values */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_ar Ray;}/* 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 supportedif (UTF8_ENABLED = TRUE) {$ str = $ this-> uni-> clean_string ($ str);} // Remove control characters $ str = remove_invisible_characters ($ str ); // shocould we filter the input data? If ($ this-> _ enable_xss === TRUE) {$ str = $ this-> security-> xss_clean ($ str) ;}// quasi-line feed on the other side, different operating systems use different line breaks, unix/n, windows/r/n, mac/r, and PHP_EOL are defined variables, representing the line breaks of php, this variable is changed to if ($ this-> _ standardize_newlines = TRUE) {if (strpos ($ str, "\ r") based on the platform ")! = FALSE) {$ str = str_replace (array ("\ r \ n", "\ r", "\ r \ n"), PHP_EOL, $ str) ;}} return $ str;} // returns/*** filter key value */function _ clean_input_keys ($ str) {if (! Preg_match ("/^ [a-z0-9: _ \/-] + $/I", $ str) {exit ('disallowed Key Characters. ');} // Clean UTF-8 if supportedif (UTF8_ENABLED === TRUE) {$ str = $ this-> uni-> clean_string ($ str);} return $ str ;} // ----------------------------------------------------------------------/*** get http request header information */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-Headerforeach ($ headers as $ key => $ val) {$ key = str_replace ('_','', strtolower ($ key); $ key = str_replace ('', '-', ucwords ($ key); $ this-> headers [$ key] = $ Val;} return $ this-> headers;} // ------------------------------------------------------------------/*** get http header information, if xxs_clean is set, filter */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];} // Configure // Determine whether the request is an ajax public function is_ajax_request () {return ($ this-> server ('http _ X_REQUESTED_WITH ') === 'xmlhttprequest ');} // -------------------------------------------------------------------- // Determine whether the request is a CLI [command line execution method] requesting public function is_cli_request () {return (php_sapi_name () === 'cli 'OR defined ('stdin '));}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.