【PHP】CI框架原始碼分析核心檔案之Input.php
前言:CI框架有部分人寫過Input.php的原始碼分析,可大多都是對其中的方法泛泛而談,根本沒有提到實現的核心細節,在此,我將自己所理解的記錄下來,希望對需要的人有用
<!--?php
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2016, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. ()
* @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology ()
* @license MIT License
* @link
* @since Version 1.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Input Class
*
* Pre-processes global input data for security
*
* @package CodeIgniter
* @subpackage Libraries
* @category Input
* @author EllisLab Dev Team
* @link /user_guide/libraries/input.html
*/
class CI_Input {
/**
* IP address of the current user
*這裡指的是當前訪問web站點的客戶端ip地址
*如果前面是一個nginx的負載均衡,後端是web伺服器,則為該負載均衡的地址
* @var string
*/
protected $ip_address = FALSE;
/**
* Allow GET array flag
*
* If set to FALSE, then $_GET will be set to an empty array.
*如果設定為false,則$_GET設定為空,也就是是否能從全域性$_GET中取資料
* @var bool
*/
protected $_allow_get_array = TRUE;
/**
* Standardize new lines flag
*
* If set to TRUE, then newlines are standardized.
*
* @var bool
*是否啟用標準換行,window\r\n linux \r
*/
protected $_standardize_newlines;
/**
* Enable XSS flag
*
* Determines whether the XSS filter is always active when
* GET, POST or COOKIE data is encountered.
* Set automatically based on config setting.
*是否啟動XSS防護,xss防護在security.php中實現
* @var bool
*/
protected $_enable_xss = FALSE;
/**
* Enable CSRF flag
*是否開啟csrf防護
* Enables a CSRF cookie token to be set.
* Set automatically based on config setting.
*
* @var bool
*/
protected $_enable_csrf = FALSE;
/**
* List of all HTTP request headers
*
* @var array
*/
protected $headers = array();
/**
* Raw input stream data
*
* Holds a cache of php://input contents
*
* @var string
*/
protected $_raw_input_stream;
/**
* Parsed input stream data
*
* Parsed from php://input at runtime
*
* @see CI_Input::input_stream()
* @var array
*/
protected $_input_stream;
protected $security;
protected $uni;
// --------------------------------------------------------------------
/**
* Class constructor
*
* Determines whether to globally enable the XSS processing
* and whether to allow the $_GET array.
*
* @return void
*/
public function __construct()
{
//讀取配置檔案中配置(是否啟動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);
$this->_standardize_newlines = (bool) config_item('standardize_newlines');
//載入Security.php
$this->security =& load_class('Security', 'core');
// Do we need the UTF-8 class?
if (UTF8_ENABLED === TRUE)
{
$this->uni =& load_class('Utf8', 'core');
}
// Sanitize global arrays-->去除全域性陣列(讓全域性陣列失效,例如將$_GET()置為空)
$this->_sanitize_globals();
// CSRF Protection check-->是否開啟CSRF保護
//啟動csrf防護&&PHP_SAPI != 'cli'
if ($this->_enable_csrf === TRUE && ! is_cli())
{
$this->security->csrf_verify();
}
log_message('info', 'Input Class Initialized');
}
// --------------------------------------------------------------------
/**
* Fetch from array
*內部方法用於從全域性陣列獲取鍵所對定的值
* Internal method used to retrieve values from global arrays.
*
* @param array &$array $_GET, $_POST, $_COOKIE, $_SERVER, etc.
* @param mixed $index Index for item to be fetched from $array
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
protected function _fetch_from_array(&$array, $index = NULL, $xss_clean = NULL)
{
//是否需要開始xss防護
is_bool($xss_clean) OR $xss_clean = $this->_enable_xss;
// If $index is NULL, it means that the whole $array is requested
//如果index為NULL的時候,那麼就是請求整個陣列
isset($index) OR $index = array_keys($array);
// allow fetching multiple keys at once
//允許一次獲取多個鍵,如果$index是鍵陣列,則開啟迭代
if (is_array($index))
{
$output = array();
foreach ($index as $key)
//迭代
$output[$key] = $this->_fetch_from_array($array, $key, $xss_clean);
}
return $output;
}
//如果這個鍵的值存在,則用$value儲存這個值
if (isset($array[$index]))
{
$value = $array[$index];
}
//如果值不存在,這檢視$index是否有陣列的標記,如果匹配到陣列的值,就作為鍵,然後取值---這樣是不是容易受到攻擊?
elseif (($count = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches)) > 1) // Does the index contain array notation
{
$value = $array;
for ($i = 0; $i < $count; $i++)
{
$key = trim($matches[0][$i], '[]');
if ($key === '') // Empty notation will return the value as array
{
break;
}
if (isset($value[$key]))
{
$value = $value[$key];
}
else
{
return NULL;
}
}
}
else
{
return NULL;
}
//xss過濾後返回值
return ($xss_clean === TRUE)
? $this->security->xss_clean($value)
: $value;
}
// --------------------------------------------------------------------
/**
* Fetch an item from the GET array
*獲取get的值
* @param mixed $index Index for item to be fetched from $_GET
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function get($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_GET, $index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from the POST array
*獲取post的值
* @param mixed $index Index for item to be fetched from $_POST
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function post($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_POST, $index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from POST data with fallback to GET
*先獲取post值,若沒有則獲取$_GET()的值
* @param string $index Index for item to be fetched from $_POST or $_GET
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function post_get($index, $xss_clean = NULL)
{
return isset($_POST[$index])
? $this->post($index, $xss_clean)
: $this->get($index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from GET data with fallback to POST
*先獲取get值,若沒有則獲取POST的值
* @param string $index Index for item to be fetched from $_GET or $_POST
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function get_post($index, $xss_clean = NULL)
{
return isset($_GET[$index])
? $this->get($index, $xss_clean)
: $this->post($index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from the COOKIE array
*獲取COOKIE的值
* @param mixed $index Index for item to be fetched from $_COOKIE
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function cookie($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from the SERVER array
*獲取$_SEVER的值
* @param mixed $index Index for item to be fetched from $_SERVER
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function server($index, $xss_clean = NULL)
{
return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
}
// ------------------------------------------------------------------------
/**
* Fetch an item from the php://input stream
*採用php://input獲取post提交的原始資料,但是Content-Type不能是multipart/form-data
*好處是更小的記憶體
* Useful when you need to access PUT, DELETE or PATCH request data.
*
* @param string $index Index for item to be fetched
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function input_stream($index = NULL, $xss_clean = NULL)
{
// Prior to PHP 5.6, the input stream can only be read once,
// so we'll need to check if we have already done that first.
if ( ! is_array($this->_input_stream))
{
// $this->raw_input_stream will trigger __get().透過觸發__get獲取資料
//parse_str函式將獲取的uri解析放入$this->_input_streams陣列中
parse_str($this->raw_input_stream, $this->_input_stream);
is_array($this->_input_stream) OR $this->_input_stream = array();
}
return $this->_fetch_from_array($this->_input_stream, $index, $xss_clean);
}
// ------------------------------------------------------------------------
/**
* Set cookie
*
* Accepts an arbitrary number of parameters (up to 7) or an associative
* array in the first parameter containing all the values.
*
* @param string|mixed[] $name Cookie name or an array containing parameters
* @param string $value Cookie value
* @param int $expire Cookie expiration time in seconds
* @param string $domain Cookie domain (e.g.: '.yourdomain.com')
* @param string $path Cookie path (default: '/')
* @param string $prefix Cookie name prefix
* @param bool $secure Whether to only transfer cookies via SSL
* @param bool $httponly Whether to only makes the cookie accessible via HTTP (no javascript)
* @return void
*/
public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = 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', 'httponly', 'name') as $item)
{
if (isset($name[$item]))
{
$$item = $name[$item];
}
}
}
//從application的config.php,獲取cookie變數的字首
if ($prefix === '' && config_item('cookie_prefix') !== '')
{
$prefix = config_item('cookie_prefix');
}
//從application的config.php,獲取domain的字首
if ($domain == '' && config_item('cookie_domain') != '')
{
$domain = config_item('cookie_domain');
}
//設定客戶端儲存Cookie_path的路徑
if ($path === '/' && config_item('cookie_path') !== '/')
{
$path = config_item('cookie_path');
}
if ($secure === FALSE && config_item('cookie_secure') === TRUE)
{
$secure = config_item('cookie_secure');
}
if ($httponly === FALSE && config_item('cookie_httponly') !== FALSE)
{
$httponly = config_item('cookie_httponly');
}
if ( ! is_numeric($expire))
{
$expire = time() - 86500;
}
else
{
$expire = ($expire > 0) ? time() + $expire : 0;
}
setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly);
}
// --------------------------------------------------------------------
/**
* Fetch the IP Address
*驗證訪問者的IP地址
* Determines and validates the visitor's IP address.
*
* @return string IP address
*/
public function ip_address()
{
if ($this->ip_address !== FALSE)
{
return $this->ip_address;
}
//使用反向代理
$proxy_ips = config_item('proxy_ips');
if ( ! empty($proxy_ips) && ! is_array($proxy_ips))
{
$proxy_ips = explode(',', str_replace(' ', '', $proxy_ips));
}
//獲取remote_add
$this->ip_address = $this->server('REMOTE_ADDR');
if ($proxy_ips)
{
//These headers can be spoofed:
//- HTTP_PROXY_USER使用代理
//- HTTP_X_FORWARDED_FOR在哪個Ip使用的代理
//- HTTP_CLIENT_IP HTTP_CLIENT_IP 是代理伺服器傳送的HTTP頭。
//- HTTP_X_CLUSTER_CLIENT_IP--Zeus
//- REMOTE_ADDR是你的客戶端跟你的伺服器“握手”時候的IP。如果使用了“匿名代理”,REMOTE_ADDR將顯示代理伺服器的IP。
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)) !== NULL)
{
// 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.
sscanf($spoof, '%[^,]', $spoof);
//檢驗是否是有效ip地址,無效勁$spoof置為NULL
if ( ! $this->valid_ip($spoof))
{
$spoof = NULL;
}
else
{
break;
}
}
}
if ($spoof)
{
for ($i = 0, $c = count($proxy_ips); $i < $c; $i++)
{
// Check if we have an IP address or a subnet
if (strpos($proxy_ips[$i], '/') === FALSE)
{
// An IP address (and not a subnet) is specified.
// We can compare right away.
//如果我們設定的代理ip,與remote_addr相等,說明得到的spoof是可信的
if ($proxy_ips[$i] === $this->ip_address)
{
$this->ip_address = $spoof;
break;
}
continue;
}
// We have a subnet ... now the heavy lifting begins --如果設定的代理IP為子網,那麼艱難的工作開始了
//如果是ipv6,分隔符為":",如果是ipv4,分隔符號則為"."
isset($separator) OR $separator = $this->valid_ip($this->ip_address, 'ipv6') ? ':' : '.';
// If the proxy entry doesn't match the IP protocol - skip it--代理設定ip與採用的ip協議不符
if (strpos($proxy_ips[$i], $separator) === FALSE)
{
continue;
}
// Convert the REMOTE_ADDR IP address to binary, if needed
//$ip與$sprintf變數未有同時被設定
if ( ! isset($ip, $sprintf))
{
//分隔符為:,明顯表示ipv6
if ($separator === ':')
{
// Make sure we're have the "full" IPv6 format
$ip = explode(':',
str_replace('::',
str_repeat(':', 9 - substr_count($this->ip_address, ':')),
$this->ip_address
)
);
for ($j = 0; $j < 8; $j++)
{
$ip[$j] = intval($ip[$j], 16);
}
$sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b';
}
else
{
//按點分隔,變成包含四個元素的ip陣列
$ip = explode('.', $this->ip_address);
//二進位制格式化字串
$sprintf = '%08b%08b%08b%08b';
}
//變成二進位制的ip地址
$ip = vsprintf($sprintf, $ip);
}
// Split the netmask length off the network address
//獲取網路號與掩碼
sscanf($proxy_ips[$i], '%[^/]/%d', $netaddr, $masklen);
// Again, an IPv6 address is most likely in a compressed form
if ($separator === ':')
{
$netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr));
for ($i = 0; $i < 8; $i++)
{
$netaddr[$i] = intval($netaddr[$i], 16);
}
}
else
{
$netaddr = explode('.', $netaddr);
}
// Convert to binary and finally compare
//如果網路號匹配,則$poof是可信的
if (strncmp($ip, vsprintf($sprintf, $netaddr), $masklen) === 0)
{
$this->ip_address = $spoof;
break;
}
}
}
}
//沒有代理且remote_add無效的ip地址,返回0.0.0.0
if ( ! $this->valid_ip($this->ip_address))
{
return $this->ip_address = '0.0.0.0';
}
return $this->ip_address;
}
// --------------------------------------------------------------------
/**
* Validate IP Address
*檢驗IP地址是否合法
* @param string $ip IP address
* @param string $which IP protocol: 'ipv4' or 'ipv6'
* @return bool
*/
public function valid_ip($ip, $which = '')
{
switch (strtolower($which))
{
case 'ipv4':
$which = FILTER_FLAG_IPV4;
break;
case 'ipv6':
$which = FILTER_FLAG_IPV6;
break;
default:
$which = NULL;
break;
}
return (bool) filter_var($ip, FILTER_VALIDATE_IP, $which);
}
// --------------------------------------------------------------------
/**
* Fetch User Agent string
*獲取客戶端資訊,通常這個可以設定不可靠
* @return string|null User Agent string or NULL if it doesn't exist
*/
public function user_agent($xss_clean = NULL)
{
return $this->_fetch_from_array($_SERVER, 'HTTP_USER_AGENT', $xss_clean);
}
// --------------------------------------------------------------------
/**
* Sanitize Globals
*消除全域性陣列
* Internal method serving for the following purposes:
*
* - Unsets $_GET data, if query strings are not enabled
* - Cleans POST, COOKIE and SERVER data
* - Standardizes newline characters to PHP_EOL
*
* @return void
*/
protected function _sanitize_globals()
{
// Is $_GET data allowed? If not we'll set the $_GET to an empty array
//如果不容許直接訪問$_GET全域性陣列,就設定全域性陣列為NULL
if ($this->_allow_get_array === FALSE)
{
$_GET = array();
}
elseif (is_array($_GET))
{
//過濾$_GET的鍵值與資料
foreach ($_GET as $key => $val)
{
$_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
}
}
// Clean $_POST Data
if (is_array($_POST))
{
foreach ($_POST as $key => $val)
{
$_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
}
}
// Clean $_COOKIE Data
if (is_array($_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
//
// note that the key names below are single quoted strings, and are not PHP variables
unset(
$_COOKIE['$Version'],
$_COOKIE['$Path'],
$_COOKIE['$Domain']
);
foreach ($_COOKIE as $key => $val)
{
if (($cookie_key = $this->_clean_input_keys($key)) !== FALSE)
{
$_COOKIE[$cookie_key] = $this->_clean_input_data($val);
}
else
{
unset($_COOKIE[$key]);
}
}
}
// Sanitize PHP_SELF
$_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);
log_message('debug', 'Global POST, GET and COOKIE data sanitized');
}
// --------------------------------------------------------------------
/**
* Clean Input Data
*
* Internal method that aids in escaping data and
* standardizing newline characters to PHP_EOL.
*
* @param string|string[] $str Input string(s)
* @return string
*/
protected function _clean_input_data($str)
{
if (is_array($str))
{
$new_array = array();
//如果傳遞的引數$str為鍵值陣列,則迭代
foreach (array_keys($str) as $key)
{
$new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($str[$key]);
}
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)
{
//刪除非utf-8的字元
$str = $this->uni->clean_string($str);
}
// Remove control characters
$str = remove_invisible_characters($str, FALSE);
// Standardize newlines if needed--windows下\r\n,linux下\n
if ($this->_standardize_newlines === TRUE)
{
return preg_replace('/(?:\r\n|[\r\n])/', PHP_EOL, $str);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Clean Keys
*
* Internal method that helps 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.
*
* @param string $str Input string
* @param bool $fatal Whether to terminate script exection
* or to return FALSE if an invalid
* key is encountered
* @return string|bool
*/
protected function _clean_input_keys($str, $fatal = TRUE)
{
//非數字字母下劃線以及-組成key,都必須過濾
if ( ! preg_match('/^[a-z0-9:_\/|-]+$/i', $str))
{
if ($fatal === TRUE)
{
return FALSE;
}
else
{
//返回503的錯誤碼
set_status_header(503);
echo 'Disallowed Key Characters.';
exit(7); // EXIT_USER_INPUT
}
}
// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE)
{
//過濾非UTF-8編碼的字元
return $this->uni->clean_string($str);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Request Headers
*
* @param bool $xss_clean Whether to apply XSS filtering
* @return array
*/
public function request_headers($xss_clean = FALSE)
{
// If header is already defined, return it immediately
if ( ! empty($this->headers))
{
return $this->headers;
}
// In Apache, you can simply call apache_request_headers()
if (function_exists('apache_request_headers'))
{
//獲得請求頭,這種方式只支援apache
return $this->headers = apache_request_headers();
}
//獲取副檔名
$this->headers['Content-Type'] = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE');
foreach ($_SERVER as $key => $val)
{
if (sscanf($key, 'HTTP_%s', $header) === 1)
{
// take SOME_HEADER and turn it into Some-Header
//字串轉為小寫,_轉成-,首字母大寫,例如:CLIENT_IP變為Client-Ip
$header = str_replace('_', ' ', strtolower($header));
$header = str_replace(' ', '-', ucwords($header));
//獲取header的陣列(透過過濾)
$this->headers[$header] = $this->_fetch_from_array($_SERVER, $key, $xss_clean);
}
}
return $this->headers;
}
// --------------------------------------------------------------------
/**
* Get Request Header
*
* Returns the value of a single member of the headers class member
*
* @param string $index Header name
* @param bool $xss_clean Whether to apply XSS filtering
* @return string|null The requested header on success or NULL on failure
*/
public function get_request_header($index, $xss_clean = FALSE)
{
static $headers;
if ( ! isset($headers))
{
//如果this->headers為空則填充this->headers
empty($this->headers) && $this->request_headers();
foreach ($this->headers as $key => $value)
{
//將其儲存在靜態陣列$headers變數中
$headers[strtolower($key)] = $value;
}
}
//取得鍵值的小寫值
$index = strtolower($index);
//如果靜態陣列中沒$index的鍵值,則返回NULL
if ( ! isset($headers[$index]))
{
return NULL;
}
//返回或者xss過濾值之後,再返回
return ($xss_clean === TRUE)
? $this->security->xss_clean($headers[$index])
: $headers[$index];
}
// --------------------------------------------------------------------
/**
* Is AJAX request?
*
* Test to see if a request contains the HTTP_X_REQUESTED_WITH header.
*判斷請求是否帶有HTTP_X_REQUESTED_WITH頭且值為xmlhttprequest,返回0或者1
* @return bool
*/
public function is_ajax_request()
{
return ( ! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
}
// --------------------------------------------------------------------
/**
* Is CLI request?
*
* Test to see if a request was made from the command line.
*
* @deprecated 3.0.0 Use is_cli() instead
* @return bool
*/
public function is_cli_request()
{
return is_cli();
}
// --------------------------------------------------------------------
/**
* Get Request Method
*獲取請求方法,返回大寫或者小寫的請求方法
* Return the request method
*
* @param bool $upper Whether to return in upper or lower case
* (default: FALSE)
* @return string
*/
public function method($upper = FALSE)
{
return ($upper)
? strtoupper($this->server('REQUEST_METHOD'))
: strtolower($this->server('REQUEST_METHOD'));
}
// ------------------------------------------------------------------------
/**
* Magic __get()
*
* Allows read access to protected properties
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
if ($name === 'raw_input_stream')
{
//用php//input獲取post的原始資料
isset($this->_raw_input_stream) OR $this->_raw_input_stream = file_get_contents('php://input');
return $this->_raw_input_stream;
}
elseif ($name === 'ip_address')
{
return $this->ip_address;
}
}
}
<!--?php
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2016, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. ()
* @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology ()
* @license MIT License
* @link
* @since Version 1.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Input Class
*
* Pre-processes global input data for security
*
* @package CodeIgniter
* @subpackage Libraries
* @category Input
* @author EllisLab Dev Team
* @link /user_guide/libraries/input.html
*/
class CI_Input {
/**
* IP address of the current user
*這裡指的是當前訪問web站點的客戶端ip地址
*如果前面是一個nginx的負載均衡,後端是web伺服器,則為該負載均衡的地址
* @var string
*/
protected $ip_address = FALSE;
/**
* Allow GET array flag
*
* If set to FALSE, then $_GET will be set to an empty array.
*如果設定為false,則$_GET設定為空,也就是是否能從全域性$_GET中取資料
* @var bool
*/
protected $_allow_get_array = TRUE;
/**
* Standardize new lines flag
*
* If set to TRUE, then newlines are standardized.
*
* @var bool
*是否啟用標準換行,window\r\n linux \r
*/
protected $_standardize_newlines;
/**
* Enable XSS flag
*
* Determines whether the XSS filter is always active when
* GET, POST or COOKIE data is encountered.
* Set automatically based on config setting.
*是否啟動XSS防護,xss防護在security.php中實現
* @var bool
*/
protected $_enable_xss = FALSE;
/**
* Enable CSRF flag
*是否開啟csrf防護
* Enables a CSRF cookie token to be set.
* Set automatically based on config setting.
*
* @var bool
*/
protected $_enable_csrf = FALSE;
/**
* List of all HTTP request headers
*
* @var array
*/
protected $headers = array();
/**
* Raw input stream data
*
* Holds a cache of php://input contents
*
* @var string
*/
protected $_raw_input_stream;
/**
* Parsed input stream data
*
* Parsed from php://input at runtime
*
* @see CI_Input::input_stream()
* @var array
*/
protected $_input_stream;
protected $security;
protected $uni;
// --------------------------------------------------------------------
/**
* Class constructor
*
* Determines whether to globally enable the XSS processing
* and whether to allow the $_GET array.
*
* @return void
*/
public function __construct()
{
//讀取配置檔案中配置(是否啟動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);
$this->_standardize_newlines = (bool) config_item('standardize_newlines');
//載入Security.php
$this->security =& load_class('Security', 'core');
// Do we need the UTF-8 class?
if (UTF8_ENABLED === TRUE)
{
$this->uni =& load_class('Utf8', 'core');
}
// Sanitize global arrays-->去除全域性陣列(讓全域性陣列失效,例如將$_GET()置為空)
$this->_sanitize_globals();
// CSRF Protection check-->是否開啟CSRF保護
//啟動csrf防護&&PHP_SAPI != 'cli'
if ($this->_enable_csrf === TRUE && ! is_cli())
{
$this->security->csrf_verify();
}
log_message('info', 'Input Class Initialized');
}
// --------------------------------------------------------------------
/**
* Fetch from array
*內部方法用於從全域性陣列獲取鍵所對定的值
* Internal method used to retrieve values from global arrays.
*
* @param array &$array $_GET, $_POST, $_COOKIE, $_SERVER, etc.
* @param mixed $index Index for item to be fetched from $array
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
protected function _fetch_from_array(&$array, $index = NULL, $xss_clean = NULL)
{
//是否需要開始xss防護
is_bool($xss_clean) OR $xss_clean = $this->_enable_xss;
// If $index is NULL, it means that the whole $array is requested
//如果index為NULL的時候,那麼就是請求整個陣列
isset($index) OR $index = array_keys($array);
// allow fetching multiple keys at once
//允許一次獲取多個鍵,如果$index是鍵陣列,則開啟迭代
if (is_array($index))
{
$output = array();
foreach ($index as $key)
//迭代
$output[$key] = $this->_fetch_from_array($array, $key, $xss_clean);
}
return $output;
}
//如果這個鍵的值存在,則用$value儲存這個值
if (isset($array[$index]))
{
$value = $array[$index];
}
//如果值不存在,這檢視$index是否有陣列的標記,如果匹配到陣列的值,就作為鍵,然後取值---這樣是不是容易受到攻擊?
elseif (($count = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $index, $matches)) > 1) // Does the index contain array notation
{
$value = $array;
for ($i = 0; $i < $count; $i++)
{
$key = trim($matches[0][$i], '[]');
if ($key === '') // Empty notation will return the value as array
{
break;
}
if (isset($value[$key]))
{
$value = $value[$key];
}
else
{
return NULL;
}
}
}
else
{
return NULL;
}
//xss過濾後返回值
return ($xss_clean === TRUE)
? $this->security->xss_clean($value)
: $value;
}
// --------------------------------------------------------------------
/**
* Fetch an item from the GET array
*獲取get的值
* @param mixed $index Index for item to be fetched from $_GET
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function get($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_GET, $index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from the POST array
*獲取post的值
* @param mixed $index Index for item to be fetched from $_POST
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function post($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_POST, $index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from POST data with fallback to GET
*先獲取post值,若沒有則獲取$_GET()的值
* @param string $index Index for item to be fetched from $_POST or $_GET
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function post_get($index, $xss_clean = NULL)
{
return isset($_POST[$index])
? $this->post($index, $xss_clean)
: $this->get($index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from GET data with fallback to POST
*先獲取get值,若沒有則獲取POST的值
* @param string $index Index for item to be fetched from $_GET or $_POST
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function get_post($index, $xss_clean = NULL)
{
return isset($_GET[$index])
? $this->get($index, $xss_clean)
: $this->post($index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from the COOKIE array
*獲取COOKIE的值
* @param mixed $index Index for item to be fetched from $_COOKIE
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function cookie($index = NULL, $xss_clean = NULL)
{
return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
}
// --------------------------------------------------------------------
/**
* Fetch an item from the SERVER array
*獲取$_SEVER的值
* @param mixed $index Index for item to be fetched from $_SERVER
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function server($index, $xss_clean = NULL)
{
return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
}
// ------------------------------------------------------------------------
/**
* Fetch an item from the php://input stream
*採用php://input獲取post提交的原始資料,但是Content-Type不能是multipart/form-data
*好處是更小的記憶體
* Useful when you need to access PUT, DELETE or PATCH request data.
*
* @param string $index Index for item to be fetched
* @param bool $xss_clean Whether to apply XSS filtering
* @return mixed
*/
public function input_stream($index = NULL, $xss_clean = NULL)
{
// Prior to PHP 5.6, the input stream can only be read once,
// so we'll need to check if we have already done that first.
if ( ! is_array($this->_input_stream))
{
// $this->raw_input_stream will trigger __get().透過觸發__get獲取資料
//parse_str函式將獲取的uri解析放入$this->_input_streams陣列中
parse_str($this->raw_input_stream, $this->_input_stream);
is_array($this->_input_stream) OR $this->_input_stream = array();
}
return $this->_fetch_from_array($this->_input_stream, $index, $xss_clean);
}
// ------------------------------------------------------------------------
/**
* Set cookie
*
* Accepts an arbitrary number of parameters (up to 7) or an associative
* array in the first parameter containing all the values.
*
* @param string|mixed[] $name Cookie name or an array containing parameters
* @param string $value Cookie value
* @param int $expire Cookie expiration time in seconds
* @param string $domain Cookie domain (e.g.: '.yourdomain.com')
* @param string $path Cookie path (default: '/')
* @param string $prefix Cookie name prefix
* @param bool $secure Whether to only transfer cookies via SSL
* @param bool $httponly Whether to only makes the cookie accessible via HTTP (no javascript)
* @return void
*/
public function set_cookie($name, $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = 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', 'httponly', 'name') as $item)
{
if (isset($name[$item]))
{
$$item = $name[$item];
}
}
}
//從application的config.php,獲取cookie變數的字首
if ($prefix === '' && config_item('cookie_prefix') !== '')
{
$prefix = config_item('cookie_prefix');
}
//從application的config.php,獲取domain的字首
if ($domain == '' && config_item('cookie_domain') != '')
{
$domain = config_item('cookie_domain');
}
//設定客戶端儲存Cookie_path的路徑
if ($path === '/' && config_item('cookie_path') !== '/')
{
$path = config_item('cookie_path');
}
if ($secure === FALSE && config_item('cookie_secure') === TRUE)
{
$secure = config_item('cookie_secure');
}
if ($httponly === FALSE && config_item('cookie_httponly') !== FALSE)
{
$httponly = config_item('cookie_httponly');
}
if ( ! is_numeric($expire))
{
$expire = time() - 86500;
}
else
{
$expire = ($expire > 0) ? time() + $expire : 0;
}
setcookie($prefix.$name, $value, $expire, $path, $domain, $secure, $httponly);
}
// --------------------------------------------------------------------
/**
* Fetch the IP Address
*驗證訪問者的IP地址
* Determines and validates the visitor's IP address.
*
* @return string IP address
*/
public function ip_address()
{
if ($this->ip_address !== FALSE)
{
return $this->ip_address;
}
//使用反向代理
$proxy_ips = config_item('proxy_ips');
if ( ! empty($proxy_ips) && ! is_array($proxy_ips))
{
$proxy_ips = explode(',', str_replace(' ', '', $proxy_ips));
}
//獲取remote_add
$this->ip_address = $this->server('REMOTE_ADDR');
if ($proxy_ips)
{
//These headers can be spoofed:
//- HTTP_PROXY_USER使用代理
//- HTTP_X_FORWARDED_FOR在哪個Ip使用的代理
//- HTTP_CLIENT_IP HTTP_CLIENT_IP 是代理伺服器傳送的HTTP頭。
//- HTTP_X_CLUSTER_CLIENT_IP--Zeus
//- REMOTE_ADDR是你的客戶端跟你的伺服器“握手”時候的IP。如果使用了“匿名代理”,REMOTE_ADDR將顯示代理伺服器的IP。
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)) !== NULL)
{
// 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.
sscanf($spoof, '%[^,]', $spoof);
//檢驗是否是有效ip地址,無效勁$spoof置為NULL
if ( ! $this->valid_ip($spoof))
{
$spoof = NULL;
}
else
{
break;
}
}
}
if ($spoof)
{
for ($i = 0, $c = count($proxy_ips); $i < $c; $i++)
{
// Check if we have an IP address or a subnet
if (strpos($proxy_ips[$i], '/') === FALSE)
{
// An IP address (and not a subnet) is specified.
// We can compare right away.
//如果我們設定的代理ip,與remote_addr相等,說明得到的spoof是可信的
if ($proxy_ips[$i] === $this->ip_address)
{
$this->ip_address = $spoof;
break;
}
continue;
}
// We have a subnet ... now the heavy lifting begins --如果設定的代理IP為子網,那麼艱難的工作開始了
//如果是ipv6,分隔符為":",如果是ipv4,分隔符號則為"."
isset($separator) OR $separator = $this->valid_ip($this->ip_address, 'ipv6') ? ':' : '.';
// If the proxy entry doesn't match the IP protocol - skip it--代理設定ip與採用的ip協議不符
if (strpos($proxy_ips[$i], $separator) === FALSE)
{
continue;
}
// Convert the REMOTE_ADDR IP address to binary, if needed
//$ip與$sprintf變數未有同時被設定
if ( ! isset($ip, $sprintf))
{
//分隔符為:,明顯表示ipv6
if ($separator === ':')
{
// Make sure we're have the "full" IPv6 format
$ip = explode(':',
str_replace('::',
str_repeat(':', 9 - substr_count($this->ip_address, ':')),
$this->ip_address
)
);
for ($j = 0; $j < 8; $j++)
{
$ip[$j] = intval($ip[$j], 16);
}
$sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b';
}
else
{
//按點分隔,變成包含四個元素的ip陣列
$ip = explode('.', $this->ip_address);
//二進位制格式化字串
$sprintf = '%08b%08b%08b%08b';
}
//變成二進位制的ip地址
$ip = vsprintf($sprintf, $ip);
}
// Split the netmask length off the network address
//獲取網路號與掩碼
sscanf($proxy_ips[$i], '%[^/]/%d', $netaddr, $masklen);
// Again, an IPv6 address is most likely in a compressed form
if ($separator === ':')
{
$netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr));
for ($i = 0; $i < 8; $i++)
{
$netaddr[$i] = intval($netaddr[$i], 16);
}
}
else
{
$netaddr = explode('.', $netaddr);
}
// Convert to binary and finally compare
//如果網路號匹配,則$poof是可信的
if (strncmp($ip, vsprintf($sprintf, $netaddr), $masklen) === 0)
{
$this->ip_address = $spoof;
break;
}
}
}
}
//沒有代理且remote_add無效的ip地址,返回0.0.0.0
if ( ! $this->valid_ip($this->ip_address))
{
return $this->ip_address = '0.0.0.0';
}
return $this->ip_address;
}
// --------------------------------------------------------------------
/**
* Validate IP Address
*檢驗IP地址是否合法
* @param string $ip IP address
* @param string $which IP protocol: 'ipv4' or 'ipv6'
* @return bool
*/
public function valid_ip($ip, $which = '')
{
switch (strtolower($which))
{
case 'ipv4':
$which = FILTER_FLAG_IPV4;
break;
case 'ipv6':
$which = FILTER_FLAG_IPV6;
break;
default:
$which = NULL;
break;
}
return (bool) filter_var($ip, FILTER_VALIDATE_IP, $which);
}
// --------------------------------------------------------------------
/**
* Fetch User Agent string
*獲取客戶端資訊,通常這個可以設定不可靠
* @return string|null User Agent string or NULL if it doesn't exist
*/
public function user_agent($xss_clean = NULL)
{
return $this->_fetch_from_array($_SERVER, 'HTTP_USER_AGENT', $xss_clean);
}
// --------------------------------------------------------------------
/**
* Sanitize Globals
*消除全域性陣列
* Internal method serving for the following purposes:
*
* - Unsets $_GET data, if query strings are not enabled
* - Cleans POST, COOKIE and SERVER data
* - Standardizes newline characters to PHP_EOL
*
* @return void
*/
protected function _sanitize_globals()
{
// Is $_GET data allowed? If not we'll set the $_GET to an empty array
//如果不容許直接訪問$_GET全域性陣列,就設定全域性陣列為NULL
if ($this->_allow_get_array === FALSE)
{
$_GET = array();
}
elseif (is_array($_GET))
{
//過濾$_GET的鍵值與資料
foreach ($_GET as $key => $val)
{
$_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
}
}
// Clean $_POST Data
if (is_array($_POST))
{
foreach ($_POST as $key => $val)
{
$_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
}
}
// Clean $_COOKIE Data
if (is_array($_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
//
// note that the key names below are single quoted strings, and are not PHP variables
unset(
$_COOKIE['$Version'],
$_COOKIE['$Path'],
$_COOKIE['$Domain']
);
foreach ($_COOKIE as $key => $val)
{
if (($cookie_key = $this->_clean_input_keys($key)) !== FALSE)
{
$_COOKIE[$cookie_key] = $this->_clean_input_data($val);
}
else
{
unset($_COOKIE[$key]);
}
}
}
// Sanitize PHP_SELF
$_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);
log_message('debug', 'Global POST, GET and COOKIE data sanitized');
}
// --------------------------------------------------------------------
/**
* Clean Input Data
*
* Internal method that aids in escaping data and
* standardizing newline characters to PHP_EOL.
*
* @param string|string[] $str Input string(s)
* @return string
*/
protected function _clean_input_data($str)
{
if (is_array($str))
{
$new_array = array();
//如果傳遞的引數$str為鍵值陣列,則迭代
foreach (array_keys($str) as $key)
{
$new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($str[$key]);
}
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)
{
//刪除非utf-8的字元
$str = $this->uni->clean_string($str);
}
// Remove control characters
$str = remove_invisible_characters($str, FALSE);
// Standardize newlines if needed--windows下\r\n,linux下\n
if ($this->_standardize_newlines === TRUE)
{
return preg_replace('/(?:\r\n|[\r\n])/', PHP_EOL, $str);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Clean Keys
*
* Internal method that helps 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.
*
* @param string $str Input string
* @param bool $fatal Whether to terminate script exection
* or to return FALSE if an invalid
* key is encountered
* @return string|bool
*/
protected function _clean_input_keys($str, $fatal = TRUE)
{
//非數字字母下劃線以及-組成key,都必須過濾
if ( ! preg_match('/^[a-z0-9:_\/|-]+$/i', $str))
{
if ($fatal === TRUE)
{
return FALSE;
}
else
{
//返回503的錯誤碼
set_status_header(503);
echo 'Disallowed Key Characters.';
exit(7); // EXIT_USER_INPUT
}
}
// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE)
{
//過濾非UTF-8編碼的字元
return $this->uni->clean_string($str);
}
return $str;
}
// --------------------------------------------------------------------
/**
* Request Headers
*
* @param bool $xss_clean Whether to apply XSS filtering
* @return array
*/
public function request_headers($xss_clean = FALSE)
{
// If header is already defined, return it immediately
if ( ! empty($this->headers))
{
return $this->headers;
}
// In Apache, you can simply call apache_request_headers()
if (function_exists('apache_request_headers'))
{
//獲得請求頭,這種方式只支援apache
return $this->headers = apache_request_headers();
}
//獲取副檔名
$this->headers['Content-Type'] = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE');
foreach ($_SERVER as $key => $val)
{
if (sscanf($key, 'HTTP_%s', $header) === 1)
{
// take SOME_HEADER and turn it into Some-Header
//字串轉為小寫,_轉成-,首字母大寫,例如:CLIENT_IP變為Client-Ip
$header = str_replace('_', ' ', strtolower($header));
$header = str_replace(' ', '-', ucwords($header));
//獲取header的陣列(透過過濾)
$this->headers[$header] = $this->_fetch_from_array($_SERVER, $key, $xss_clean);
}
}
return $this->headers;
}
// --------------------------------------------------------------------
/**
* Get Request Header
*
* Returns the value of a single member of the headers class member
*
* @param string $index Header name
* @param bool $xss_clean Whether to apply XSS filtering
* @return string|null The requested header on success or NULL on failure
*/
public function get_request_header($index, $xss_clean = FALSE)
{
static $headers;
if ( ! isset($headers))
{
//如果this->headers為空則填充this->headers
empty($this->headers) && $this->request_headers();
foreach ($this->headers as $key => $value)
{
//將其儲存在靜態陣列$headers變數中
$headers[strtolower($key)] = $value;
}
}
//取得鍵值的小寫值
$index = strtolower($index);
//如果靜態陣列中沒$index的鍵值,則返回NULL
if ( ! isset($headers[$index]))
{
return NULL;
}
//返回或者xss過濾值之後,再返回
return ($xss_clean === TRUE)
? $this->security->xss_clean($headers[$index])
: $headers[$index];
}
// --------------------------------------------------------------------
/**
* Is AJAX request?
*
* Test to see if a request contains the HTTP_X_REQUESTED_WITH header.
*判斷請求是否帶有HTTP_X_REQUESTED_WITH頭且值為xmlhttprequest,返回0或者1
* @return bool
*/
public function is_ajax_request()
{
return ( ! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');
}
// --------------------------------------------------------------------
/**
* Is CLI request?
*
* Test to see if a request was made from the command line.
*
* @deprecated 3.0.0 Use is_cli() instead
* @return bool
*/
public function is_cli_request()
{
return is_cli();
}
// --------------------------------------------------------------------
/**
* Get Request Method
*獲取請求方法,返回大寫或者小寫的請求方法
* Return the request method
*
* @param bool $upper Whether to return in upper or lower case
* (default: FALSE)
* @return string
*/
public function method($upper = FALSE)
{
return ($upper)
? strtoupper($this->server('REQUEST_METHOD'))
: strtolower($this->server('REQUEST_METHOD'));
}
// ------------------------------------------------------------------------
/**
* Magic __get()
*
* Allows read access to protected properties
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
if ($name === 'raw_input_stream')
{
//用php//input獲取post的原始資料
isset($this->_raw_input_stream) OR $this->_raw_input_stream = file_get_contents('php://input');
return $this->_raw_input_stream;
}
elseif ($name === 'ip_address')
{
return $this->ip_address;
}
}
}
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/30221425/viewspace-2088669/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 【PHP】CI框架原始碼分析核心檔案之Loader.phpPHP框架原始碼
- 【PHP】CI框架原始碼分析核心檔案之Utf8.phpPHP框架原始碼
- 【PHP】CI框架原始碼分析核心檔案之Controller.phpPHP框架原始碼Controller
- 【PHP】CI框架原始碼DB.php(資料庫類)PHP框架原始碼資料庫
- vue原始碼分析系列之入口檔案分析Vue原始碼
- 鴻蒙輕核心原始碼分析:檔案系統LittleFS鴻蒙原始碼
- workerman 框架原始碼核心分析和註解框架原始碼
- PHP JWT CI 框架PHPJWT框架
- PHP底層核心原始碼之變數PHP原始碼變數
- PHP檔案上傳原始碼分析(RFC1867)PHP原始碼
- MyBatis原始碼分析之核心處理層MyBatis原始碼
- PHP檔案分享系統原始碼PHP原始碼
- CI框架原始碼閱讀筆記6 擴充套件鉤子 Hook.php框架原始碼筆記套件HookPHP
- CI框架原始碼解讀--ROUTE和URL類框架原始碼
- YARN 核心原始碼分析Yarn原始碼
- mmap核心原始碼分析原始碼
- 爬蟲框架Webmagic原始碼分析之Spider爬蟲框架Web原始碼IDE
- Linux核心原始碼分析之setup_arch (四)Linux原始碼
- Linux核心原始碼分析之setup_arch (二)Linux原始碼
- Linux核心原始碼分析之set_arch (一)Linux原始碼
- Linux核心原始碼分析之setup_arch (三)Linux原始碼
- 併發程式設計之 SynchronousQueue 核心原始碼分析程式設計原始碼
- workerman 網路框架原始碼核心分析和註解 over 篇框架原始碼
- ThinkPHP3.1.3原始碼分析(一) 入口檔案分析PHP原始碼
- NIO框架之MINA原始碼解析(二):mina核心引擎框架原始碼
- Guava 原始碼分析之 EventBus 原始碼分析Guava原始碼
- paypal之nodejs 框架 Kraken-js 原始碼分析NodeJS框架原始碼
- 【集合框架】JDK1.8原始碼分析之HashMap(一)框架JDK原始碼HashMap
- 【集合框架】JDK1.8原始碼分析之ArrayList(六)框架JDK原始碼
- 【集合框架】JDK1.8原始碼分析之TreeMap(五)框架JDK原始碼
- 【PHP7原始碼分析】PHP7原始碼研究之淺談Zend虛擬機器PHP原始碼虛擬機
- 【核心檔案系統】原始碼閱讀stat.h原始碼
- MJRefresh原始碼框架分析原始碼框架
- Android 原始碼分析之 AsyncTask 原始碼分析Android原始碼
- 專案中常用的 .env 檔案原理原始碼分析原始碼
- 【集合框架】JDK1.8原始碼分析之LinkedHashMap(二)框架JDK原始碼HashMap
- 【集合框架】JDK1.8原始碼分析之Collections && Arrays(十)框架JDK原始碼
- 【集合框架】JDK1.8原始碼分析之LinkedList(七)框架JDK原始碼