Request.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. class Request
  13. {
  14. /**
  15. * @var object 对象实例
  16. */
  17. protected static $instance;
  18. protected $method;
  19. /**
  20. * @var string 域名(含协议和端口)
  21. */
  22. protected $domain;
  23. /**
  24. * @var string URL地址
  25. */
  26. protected $url;
  27. /**
  28. * @var string 基础URL
  29. */
  30. protected $baseUrl;
  31. /**
  32. * @var string 当前执行的文件
  33. */
  34. protected $baseFile;
  35. /**
  36. * @var string 访问的ROOT地址
  37. */
  38. protected $root;
  39. /**
  40. * @var string pathinfo
  41. */
  42. protected $pathinfo;
  43. /**
  44. * @var string pathinfo(不含后缀)
  45. */
  46. protected $path;
  47. /**
  48. * @var array 当前路由信息
  49. */
  50. protected $routeInfo = [];
  51. /**
  52. * @var array 环境变量
  53. */
  54. protected $env;
  55. /**
  56. * @var array 当前调度信息
  57. */
  58. protected $dispatch = [];
  59. protected $module;
  60. protected $controller;
  61. protected $action;
  62. // 当前语言集
  63. protected $langset;
  64. /**
  65. * @var array 请求参数
  66. */
  67. protected $param = [];
  68. protected $get = [];
  69. protected $post = [];
  70. protected $request = [];
  71. protected $route = [];
  72. protected $put;
  73. protected $session = [];
  74. protected $file = [];
  75. protected $cookie = [];
  76. protected $server = [];
  77. protected $header = [];
  78. /**
  79. * @var array 资源类型
  80. */
  81. protected $mimeType = [
  82. 'xml' => 'application/xml,text/xml,application/x-xml',
  83. 'json' => 'application/json,text/x-json,application/jsonrequest,text/json',
  84. 'js' => 'text/javascript,application/javascript,application/x-javascript',
  85. 'css' => 'text/css',
  86. 'rss' => 'application/rss+xml',
  87. 'yaml' => 'application/x-yaml,text/yaml',
  88. 'atom' => 'application/atom+xml',
  89. 'pdf' => 'application/pdf',
  90. 'text' => 'text/plain',
  91. 'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
  92. 'csv' => 'text/csv',
  93. 'html' => 'text/html,application/xhtml+xml,*/*',
  94. ];
  95. protected $content;
  96. // 全局过滤规则
  97. protected $filter;
  98. // Hook扩展方法
  99. protected static $hook = [];
  100. // 绑定的属性
  101. protected $bind = [];
  102. // php://input
  103. protected $input;
  104. // 请求缓存
  105. protected $cache;
  106. // 缓存是否检查
  107. protected $isCheckCache;
  108. /**
  109. * 是否合并Param
  110. * @var bool
  111. */
  112. protected $mergeParam = false;
  113. /**
  114. * 构造函数
  115. * @access protected
  116. * @param array $options 参数
  117. */
  118. protected function __construct($options = [])
  119. {
  120. foreach ($options as $name => $item) {
  121. if (property_exists($this, $name)) {
  122. $this->$name = $item;
  123. }
  124. }
  125. if (is_null($this->filter)) {
  126. $this->filter = Config::get('default_filter');
  127. }
  128. // 保存 php://input
  129. $this->input = file_get_contents('php://input');
  130. }
  131. public function __call($method, $args)
  132. {
  133. if (array_key_exists($method, self::$hook)) {
  134. array_unshift($args, $this);
  135. return call_user_func_array(self::$hook[$method], $args);
  136. } else {
  137. throw new Exception('method not exists:' . __CLASS__ . '->' . $method);
  138. }
  139. }
  140. /**
  141. * Hook 方法注入
  142. * @access public
  143. * @param string|array $method 方法名
  144. * @param mixed $callback callable
  145. * @return void
  146. */
  147. public static function hook($method, $callback = null)
  148. {
  149. if (is_array($method)) {
  150. self::$hook = array_merge(self::$hook, $method);
  151. } else {
  152. self::$hook[$method] = $callback;
  153. }
  154. }
  155. /**
  156. * 初始化
  157. * @access public
  158. * @param array $options 参数
  159. * @return \think\Request
  160. */
  161. public static function instance($options = [])
  162. {
  163. if (is_null(self::$instance)) {
  164. self::$instance = new static($options);
  165. }
  166. return self::$instance;
  167. }
  168. /**
  169. * 销毁当前请求对象
  170. * @access public
  171. * @return void
  172. */
  173. public static function destroy()
  174. {
  175. if (!is_null(self::$instance)) {
  176. self::$instance = null;
  177. }
  178. }
  179. /**
  180. * 创建一个URL请求
  181. * @access public
  182. * @param string $uri URL地址
  183. * @param string $method 请求类型
  184. * @param array $params 请求参数
  185. * @param array $cookie
  186. * @param array $files
  187. * @param array $server
  188. * @param string $content
  189. * @return \think\Request
  190. */
  191. public static function create($uri, $method = 'GET', $params = [], $cookie = [], $files = [], $server = [], $content = null)
  192. {
  193. $server['PATH_INFO'] = '';
  194. $server['REQUEST_METHOD'] = strtoupper($method);
  195. $info = parse_url($uri);
  196. if (isset($info['host'])) {
  197. $server['SERVER_NAME'] = $info['host'];
  198. $server['HTTP_HOST'] = $info['host'];
  199. }
  200. if (isset($info['scheme'])) {
  201. if ('https' === $info['scheme']) {
  202. $server['HTTPS'] = 'on';
  203. $server['SERVER_PORT'] = 443;
  204. } else {
  205. unset($server['HTTPS']);
  206. $server['SERVER_PORT'] = 80;
  207. }
  208. }
  209. if (isset($info['port'])) {
  210. $server['SERVER_PORT'] = $info['port'];
  211. $server['HTTP_HOST'] = $server['HTTP_HOST'] . ':' . $info['port'];
  212. }
  213. if (isset($info['user'])) {
  214. $server['PHP_AUTH_USER'] = $info['user'];
  215. }
  216. if (isset($info['pass'])) {
  217. $server['PHP_AUTH_PW'] = $info['pass'];
  218. }
  219. if (!isset($info['path'])) {
  220. $info['path'] = '/';
  221. }
  222. $options = [];
  223. $options[strtolower($method)] = $params;
  224. $queryString = '';
  225. if (isset($info['query'])) {
  226. parse_str(html_entity_decode($info['query']), $query);
  227. if (!empty($params)) {
  228. $params = array_replace($query, $params);
  229. $queryString = http_build_query($params, '', '&');
  230. } else {
  231. $params = $query;
  232. $queryString = $info['query'];
  233. }
  234. } elseif (!empty($params)) {
  235. $queryString = http_build_query($params, '', '&');
  236. }
  237. if ($queryString) {
  238. parse_str($queryString, $get);
  239. $options['get'] = isset($options['get']) ? array_merge($get, $options['get']) : $get;
  240. }
  241. $server['REQUEST_URI'] = $info['path'] . ('' !== $queryString ? '?' . $queryString : '');
  242. $server['QUERY_STRING'] = $queryString;
  243. $options['cookie'] = $cookie;
  244. $options['param'] = $params;
  245. $options['file'] = $files;
  246. $options['server'] = $server;
  247. $options['url'] = $server['REQUEST_URI'];
  248. $options['baseUrl'] = $info['path'];
  249. $options['pathinfo'] = '/' == $info['path'] ? '/' : ltrim($info['path'], '/');
  250. $options['method'] = $server['REQUEST_METHOD'];
  251. $options['domain'] = isset($info['scheme']) ? $info['scheme'] . '://' . $server['HTTP_HOST'] : '';
  252. $options['content'] = $content;
  253. self::$instance = new self($options);
  254. return self::$instance;
  255. }
  256. /**
  257. * 设置或获取当前包含协议的域名
  258. * @access public
  259. * @param string $domain 域名
  260. * @return string
  261. */
  262. public function domain($domain = null)
  263. {
  264. if (!is_null($domain)) {
  265. $this->domain = $domain;
  266. return $this;
  267. } elseif (!$this->domain) {
  268. $this->domain = $this->scheme() . '://' . $this->host();
  269. }
  270. return $this->domain;
  271. }
  272. /**
  273. * 设置或获取当前完整URL 包括QUERY_STRING
  274. * @access public
  275. * @param string|true $url URL地址 true 带域名获取
  276. * @return string
  277. */
  278. public function url($url = null)
  279. {
  280. if (!is_null($url) && true !== $url) {
  281. $this->url = $url;
  282. return $this;
  283. } elseif (!$this->url) {
  284. if (IS_CLI) {
  285. $this->url = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
  286. } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
  287. $this->url = $_SERVER['HTTP_X_REWRITE_URL'];
  288. } elseif (isset($_SERVER['REQUEST_URI'])) {
  289. $this->url = $_SERVER['REQUEST_URI'];
  290. } elseif (isset($_SERVER['ORIG_PATH_INFO'])) {
  291. $this->url = $_SERVER['ORIG_PATH_INFO'] . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '');
  292. } else {
  293. $this->url = '';
  294. }
  295. }
  296. return true === $url ? $this->domain() . $this->url : $this->url;
  297. }
  298. /**
  299. * 设置或获取当前URL 不含QUERY_STRING
  300. * @access public
  301. * @param string $url URL地址
  302. * @return string
  303. */
  304. public function baseUrl($url = null)
  305. {
  306. if (!is_null($url) && true !== $url) {
  307. $this->baseUrl = $url;
  308. return $this;
  309. } elseif (!$this->baseUrl) {
  310. $str = $this->url();
  311. $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
  312. }
  313. return true === $url ? $this->domain() . $this->baseUrl : $this->baseUrl;
  314. }
  315. /**
  316. * 设置或获取当前执行的文件 SCRIPT_NAME
  317. * @access public
  318. * @param string $file 当前执行的文件
  319. * @return string
  320. */
  321. public function baseFile($file = null)
  322. {
  323. if (!is_null($file) && true !== $file) {
  324. $this->baseFile = $file;
  325. return $this;
  326. } elseif (!$this->baseFile) {
  327. $url = '';
  328. if (!IS_CLI) {
  329. $script_name = basename($_SERVER['SCRIPT_FILENAME']);
  330. if (basename($_SERVER['SCRIPT_NAME']) === $script_name) {
  331. $url = $_SERVER['SCRIPT_NAME'];
  332. } elseif (basename($_SERVER['PHP_SELF']) === $script_name) {
  333. $url = $_SERVER['PHP_SELF'];
  334. } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $script_name) {
  335. $url = $_SERVER['ORIG_SCRIPT_NAME'];
  336. } elseif (($pos = strpos($_SERVER['PHP_SELF'], '/' . $script_name)) !== false) {
  337. $url = substr($_SERVER['SCRIPT_NAME'], 0, $pos) . '/' . $script_name;
  338. } elseif (isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'], $_SERVER['DOCUMENT_ROOT']) === 0) {
  339. $url = str_replace('\\', '/', str_replace($_SERVER['DOCUMENT_ROOT'], '', $_SERVER['SCRIPT_FILENAME']));
  340. }
  341. }
  342. $this->baseFile = $url;
  343. }
  344. return true === $file ? $this->domain() . $this->baseFile : $this->baseFile;
  345. }
  346. /**
  347. * 设置或获取URL访问根地址
  348. * @access public
  349. * @param string $url URL地址
  350. * @return string
  351. */
  352. public function root($url = null)
  353. {
  354. if (!is_null($url) && true !== $url) {
  355. $this->root = $url;
  356. return $this;
  357. } elseif (!$this->root) {
  358. $file = $this->baseFile();
  359. if ($file && 0 !== strpos($this->url(), $file)) {
  360. $file = str_replace('\\', '/', dirname($file));
  361. }
  362. $this->root = rtrim($file, '/');
  363. }
  364. return true === $url ? $this->domain() . $this->root : $this->root;
  365. }
  366. /**
  367. * 获取当前请求URL的pathinfo信息(含URL后缀)
  368. * @access public
  369. * @return string
  370. */
  371. public function pathinfo()
  372. {
  373. if (is_null($this->pathinfo)) {
  374. if (isset($_GET[Config::get('var_pathinfo')])) {
  375. // 判断URL里面是否有兼容模式参数
  376. $_SERVER['PATH_INFO'] = $_GET[Config::get('var_pathinfo')];
  377. unset($_GET[Config::get('var_pathinfo')]);
  378. } elseif (IS_CLI) {
  379. // CLI模式下 index.php module/controller/action/params/...
  380. $_SERVER['PATH_INFO'] = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
  381. }
  382. // 分析PATHINFO信息
  383. if (!isset($_SERVER['PATH_INFO'])) {
  384. foreach (Config::get('pathinfo_fetch') as $type) {
  385. if (!empty($_SERVER[$type])) {
  386. $_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type], $_SERVER['SCRIPT_NAME'])) ?
  387. substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME'])) : $_SERVER[$type];
  388. break;
  389. }
  390. }
  391. }
  392. $this->pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : ltrim($_SERVER['PATH_INFO'], '/');
  393. }
  394. return $this->pathinfo;
  395. }
  396. /**
  397. * 获取当前请求URL的pathinfo信息(不含URL后缀)
  398. * @access public
  399. * @return string
  400. */
  401. public function path()
  402. {
  403. if (is_null($this->path)) {
  404. $suffix = Config::get('url_html_suffix');
  405. $pathinfo = $this->pathinfo();
  406. if (false === $suffix) {
  407. // 禁止伪静态访问
  408. $this->path = $pathinfo;
  409. } elseif ($suffix) {
  410. // 去除正常的URL后缀
  411. $this->path = preg_replace('/\.(' . ltrim($suffix, '.') . ')$/i', '', $pathinfo);
  412. } else {
  413. // 允许任何后缀访问
  414. $this->path = preg_replace('/\.' . $this->ext() . '$/i', '', $pathinfo);
  415. }
  416. }
  417. return $this->path;
  418. }
  419. /**
  420. * 当前URL的访问后缀
  421. * @access public
  422. * @return string
  423. */
  424. public function ext()
  425. {
  426. return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
  427. }
  428. /**
  429. * 获取当前请求的时间
  430. * @access public
  431. * @param bool $float 是否使用浮点类型
  432. * @return integer|float
  433. */
  434. public function time($float = false)
  435. {
  436. return $float ? $_SERVER['REQUEST_TIME_FLOAT'] : $_SERVER['REQUEST_TIME'];
  437. }
  438. /**
  439. * 当前请求的资源类型
  440. * @access public
  441. * @return false|string
  442. */
  443. public function type()
  444. {
  445. $accept = $this->server('HTTP_ACCEPT');
  446. if (empty($accept)) {
  447. return false;
  448. }
  449. foreach ($this->mimeType as $key => $val) {
  450. $array = explode(',', $val);
  451. foreach ($array as $k => $v) {
  452. if (stristr($accept, $v)) {
  453. return $key;
  454. }
  455. }
  456. }
  457. return false;
  458. }
  459. /**
  460. * 设置资源类型
  461. * @access public
  462. * @param string|array $type 资源类型名
  463. * @param string $val 资源类型
  464. * @return void
  465. */
  466. public function mimeType($type, $val = '')
  467. {
  468. if (is_array($type)) {
  469. $this->mimeType = array_merge($this->mimeType, $type);
  470. } else {
  471. $this->mimeType[$type] = $val;
  472. }
  473. }
  474. /**
  475. * 当前的请求类型
  476. * @access public
  477. * @param bool $method true 获取原始请求类型
  478. * @return string
  479. */
  480. public function method($method = false)
  481. {
  482. if (true === $method) {
  483. // 获取原始请求类型
  484. return $this->server('REQUEST_METHOD') ?: 'GET';
  485. } elseif (!$this->method) {
  486. if (isset($_POST[Config::get('var_method')])) {
  487. $this->method = strtoupper($_POST[Config::get('var_method')]);
  488. $this->{$this->method}($_POST);
  489. } elseif (isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
  490. $this->method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  491. } else {
  492. $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
  493. }
  494. }
  495. return $this->method;
  496. }
  497. /**
  498. * 是否为GET请求
  499. * @access public
  500. * @return bool
  501. */
  502. public function isGet()
  503. {
  504. return $this->method() == 'GET';
  505. }
  506. /**
  507. * 是否为POST请求
  508. * @access public
  509. * @return bool
  510. */
  511. public function isPost()
  512. {
  513. return $this->method() == 'POST';
  514. }
  515. /**
  516. * 是否为PUT请求
  517. * @access public
  518. * @return bool
  519. */
  520. public function isPut()
  521. {
  522. return $this->method() == 'PUT';
  523. }
  524. /**
  525. * 是否为DELTE请求
  526. * @access public
  527. * @return bool
  528. */
  529. public function isDelete()
  530. {
  531. return $this->method() == 'DELETE';
  532. }
  533. /**
  534. * 是否为HEAD请求
  535. * @access public
  536. * @return bool
  537. */
  538. public function isHead()
  539. {
  540. return $this->method() == 'HEAD';
  541. }
  542. /**
  543. * 是否为PATCH请求
  544. * @access public
  545. * @return bool
  546. */
  547. public function isPatch()
  548. {
  549. return $this->method() == 'PATCH';
  550. }
  551. /**
  552. * 是否为OPTIONS请求
  553. * @access public
  554. * @return bool
  555. */
  556. public function isOptions()
  557. {
  558. return $this->method() == 'OPTIONS';
  559. }
  560. /**
  561. * 是否为cli
  562. * @access public
  563. * @return bool
  564. */
  565. public function isCli()
  566. {
  567. return PHP_SAPI == 'cli';
  568. }
  569. /**
  570. * 是否为cgi
  571. * @access public
  572. * @return bool
  573. */
  574. public function isCgi()
  575. {
  576. return strpos(PHP_SAPI, 'cgi') === 0;
  577. }
  578. /**
  579. * 获取当前请求的参数
  580. * @access public
  581. * @param string|array $name 变量名
  582. * @param mixed $default 默认值
  583. * @param string|array $filter 过滤方法
  584. * @return mixed
  585. */
  586. public function param($name = '', $default = null, $filter = '')
  587. {
  588. if (empty($this->mergeParam)) {
  589. $method = $this->method(true);
  590. // 自动获取请求变量
  591. switch ($method) {
  592. case 'POST':
  593. $vars = $this->post(false);
  594. break;
  595. case 'PUT':
  596. case 'DELETE':
  597. case 'PATCH':
  598. $vars = $this->put(false);
  599. break;
  600. default:
  601. $vars = [];
  602. }
  603. // 当前请求参数和URL地址中的参数合并
  604. $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
  605. $this->mergeParam = true;
  606. }
  607. if (true === $name) {
  608. // 获取包含文件上传信息的数组
  609. $file = $this->file();
  610. $data = is_array($file) ? array_merge($this->param, $file) : $this->param;
  611. return $this->input($data, '', $default, $filter);
  612. }
  613. return $this->input($this->param, $name, $default, $filter);
  614. }
  615. /**
  616. * 设置获取路由参数
  617. * @access public
  618. * @param string|array $name 变量名
  619. * @param mixed $default 默认值
  620. * @param string|array $filter 过滤方法
  621. * @return mixed
  622. */
  623. public function route($name = '', $default = null, $filter = '')
  624. {
  625. if (is_array($name)) {
  626. $this->param = [];
  627. $this->mergeParam = false;
  628. return $this->route = array_merge($this->route, $name);
  629. }
  630. return $this->input($this->route, $name, $default, $filter);
  631. }
  632. /**
  633. * 设置获取GET参数
  634. * @access public
  635. * @param string|array $name 变量名
  636. * @param mixed $default 默认值
  637. * @param string|array $filter 过滤方法
  638. * @return mixed
  639. */
  640. public function get($name = '', $default = null, $filter = '')
  641. {
  642. if (empty($this->get)) {
  643. $this->get = $_GET;
  644. }
  645. if (is_array($name)) {
  646. $this->param = [];
  647. $this->mergeParam = false;
  648. return $this->get = array_merge($this->get, $name);
  649. }
  650. return $this->input($this->get, $name, $default, $filter);
  651. }
  652. /**
  653. * 设置获取POST参数
  654. * @access public
  655. * @param string $name 变量名
  656. * @param mixed $default 默认值
  657. * @param string|array $filter 过滤方法
  658. * @return mixed
  659. */
  660. public function post($name = '', $default = null, $filter = '')
  661. {
  662. if (empty($this->post)) {
  663. $content = $this->input;
  664. if (empty($_POST) && false !== strpos($this->contentType(), 'application/json')) {
  665. $this->post = (array) json_decode($content, true);
  666. } else {
  667. $this->post = $_POST;
  668. }
  669. }
  670. if (is_array($name)) {
  671. $this->param = [];
  672. $this->mergeParam = false;
  673. return $this->post = array_merge($this->post, $name);
  674. }
  675. return $this->input($this->post, $name, $default, $filter);
  676. }
  677. /**
  678. * 设置获取PUT参数
  679. * @access public
  680. * @param string|array $name 变量名
  681. * @param mixed $default 默认值
  682. * @param string|array $filter 过滤方法
  683. * @return mixed
  684. */
  685. public function put($name = '', $default = null, $filter = '')
  686. {
  687. if (is_null($this->put)) {
  688. $content = $this->input;
  689. if (false !== strpos($this->contentType(), 'application/json')) {
  690. $this->put = (array) json_decode($content, true);
  691. } else {
  692. parse_str($content, $this->put);
  693. }
  694. }
  695. if (is_array($name)) {
  696. $this->param = [];
  697. $this->mergeParam = false;
  698. return $this->put = is_null($this->put) ? $name : array_merge($this->put, $name);
  699. }
  700. return $this->input($this->put, $name, $default, $filter);
  701. }
  702. /**
  703. * 设置获取DELETE参数
  704. * @access public
  705. * @param string|array $name 变量名
  706. * @param mixed $default 默认值
  707. * @param string|array $filter 过滤方法
  708. * @return mixed
  709. */
  710. public function delete($name = '', $default = null, $filter = '')
  711. {
  712. return $this->put($name, $default, $filter);
  713. }
  714. /**
  715. * 设置获取PATCH参数
  716. * @access public
  717. * @param string|array $name 变量名
  718. * @param mixed $default 默认值
  719. * @param string|array $filter 过滤方法
  720. * @return mixed
  721. */
  722. public function patch($name = '', $default = null, $filter = '')
  723. {
  724. return $this->put($name, $default, $filter);
  725. }
  726. /**
  727. * 获取request变量
  728. * @param string $name 数据名称
  729. * @param string $default 默认值
  730. * @param string|array $filter 过滤方法
  731. * @return mixed
  732. */
  733. public function request($name = '', $default = null, $filter = '')
  734. {
  735. if (empty($this->request)) {
  736. $this->request = $_REQUEST;
  737. }
  738. if (is_array($name)) {
  739. $this->param = [];
  740. $this->mergeParam = false;
  741. return $this->request = array_merge($this->request, $name);
  742. }
  743. return $this->input($this->request, $name, $default, $filter);
  744. }
  745. /**
  746. * 获取session数据
  747. * @access public
  748. * @param string|array $name 数据名称
  749. * @param string $default 默认值
  750. * @param string|array $filter 过滤方法
  751. * @return mixed
  752. */
  753. public function session($name = '', $default = null, $filter = '')
  754. {
  755. if (empty($this->session)) {
  756. $this->session = Session::get();
  757. }
  758. if (is_array($name)) {
  759. return $this->session = array_merge($this->session, $name);
  760. }
  761. return $this->input($this->session, $name, $default, $filter);
  762. }
  763. /**
  764. * 获取cookie参数
  765. * @access public
  766. * @param string|array $name 数据名称
  767. * @param string $default 默认值
  768. * @param string|array $filter 过滤方法
  769. * @return mixed
  770. */
  771. public function cookie($name = '', $default = null, $filter = '')
  772. {
  773. if (empty($this->cookie)) {
  774. $this->cookie = Cookie::get();
  775. }
  776. if (is_array($name)) {
  777. return $this->cookie = array_merge($this->cookie, $name);
  778. } elseif (!empty($name)) {
  779. $data = Cookie::has($name) ? Cookie::get($name) : $default;
  780. } else {
  781. $data = $this->cookie;
  782. }
  783. // 解析过滤器
  784. $filter = $this->getFilter($filter, $default);
  785. if (is_array($data)) {
  786. array_walk_recursive($data, [$this, 'filterValue'], $filter);
  787. reset($data);
  788. } else {
  789. $this->filterValue($data, $name, $filter);
  790. }
  791. return $data;
  792. }
  793. /**
  794. * 获取server参数
  795. * @access public
  796. * @param string|array $name 数据名称
  797. * @param string $default 默认值
  798. * @param string|array $filter 过滤方法
  799. * @return mixed
  800. */
  801. public function server($name = '', $default = null, $filter = '')
  802. {
  803. if (empty($this->server)) {
  804. $this->server = $_SERVER;
  805. }
  806. if (is_array($name)) {
  807. return $this->server = array_merge($this->server, $name);
  808. }
  809. return $this->input($this->server, false === $name ? false : strtoupper($name), $default, $filter);
  810. }
  811. /**
  812. * 获取上传的文件信息
  813. * @access public
  814. * @param string|array $name 名称
  815. * @return null|array|\think\File
  816. */
  817. public function file($name = '')
  818. {
  819. if (empty($this->file)) {
  820. $this->file = isset($_FILES) ? $_FILES : [];
  821. }
  822. if (is_array($name)) {
  823. return $this->file = array_merge($this->file, $name);
  824. }
  825. $files = $this->file;
  826. if (!empty($files)) {
  827. // 处理上传文件
  828. $array = [];
  829. foreach ($files as $key => $file) {
  830. if (is_array($file['name'])) {
  831. $item = [];
  832. $keys = array_keys($file);
  833. $count = count($file['name']);
  834. for ($i = 0; $i < $count; $i++) {
  835. if (empty($file['tmp_name'][$i]) || !is_file($file['tmp_name'][$i])) {
  836. continue;
  837. }
  838. $temp['key'] = $key;
  839. foreach ($keys as $_key) {
  840. $temp[$_key] = $file[$_key][$i];
  841. }
  842. $item[] = (new File($temp['tmp_name']))->setUploadInfo($temp);
  843. }
  844. $array[$key] = $item;
  845. } else {
  846. if ($file instanceof File) {
  847. $array[$key] = $file;
  848. } else {
  849. if (empty($file['tmp_name']) || !is_file($file['tmp_name'])) {
  850. continue;
  851. }
  852. $array[$key] = (new File($file['tmp_name']))->setUploadInfo($file);
  853. }
  854. }
  855. }
  856. if (strpos($name, '.')) {
  857. list($name, $sub) = explode('.', $name);
  858. }
  859. if ('' === $name) {
  860. // 获取全部文件
  861. return $array;
  862. } elseif (isset($sub) && isset($array[$name][$sub])) {
  863. return $array[$name][$sub];
  864. } elseif (isset($array[$name])) {
  865. return $array[$name];
  866. }
  867. }
  868. return;
  869. }
  870. /**
  871. * 获取环境变量
  872. * @param string|array $name 数据名称
  873. * @param string $default 默认值
  874. * @param string|array $filter 过滤方法
  875. * @return mixed
  876. */
  877. public function env($name = '', $default = null, $filter = '')
  878. {
  879. if (empty($this->env)) {
  880. $this->env = $_ENV;
  881. }
  882. if (is_array($name)) {
  883. return $this->env = array_merge($this->env, $name);
  884. }
  885. return $this->input($this->env, false === $name ? false : strtoupper($name), $default, $filter);
  886. }
  887. /**
  888. * 设置或者获取当前的Header
  889. * @access public
  890. * @param string|array $name header名称
  891. * @param string $default 默认值
  892. * @return string
  893. */
  894. public function header($name = '', $default = null)
  895. {
  896. if (empty($this->header)) {
  897. $header = [];
  898. if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
  899. $header = $result;
  900. } else {
  901. $server = $this->server ?: $_SERVER;
  902. foreach ($server as $key => $val) {
  903. if (0 === strpos($key, 'HTTP_')) {
  904. $key = str_replace('_', '-', strtolower(substr($key, 5)));
  905. $header[$key] = $val;
  906. }
  907. }
  908. if (isset($server['CONTENT_TYPE'])) {
  909. $header['content-type'] = $server['CONTENT_TYPE'];
  910. }
  911. if (isset($server['CONTENT_LENGTH'])) {
  912. $header['content-length'] = $server['CONTENT_LENGTH'];
  913. }
  914. }
  915. $this->header = array_change_key_case($header);
  916. }
  917. if (is_array($name)) {
  918. return $this->header = array_merge($this->header, $name);
  919. }
  920. if ('' === $name) {
  921. return $this->header;
  922. }
  923. $name = str_replace('_', '-', strtolower($name));
  924. return isset($this->header[$name]) ? $this->header[$name] : $default;
  925. }
  926. /**
  927. * 获取变量 支持过滤和默认值
  928. * @param array $data 数据源
  929. * @param string|false $name 字段名
  930. * @param mixed $default 默认值
  931. * @param string|array $filter 过滤函数
  932. * @return mixed
  933. */
  934. public function input($data = [], $name = '', $default = null, $filter = '')
  935. {
  936. if (false === $name) {
  937. // 获取原始数据
  938. return $data;
  939. }
  940. $name = (string) $name;
  941. if ('' != $name) {
  942. // 解析name
  943. if (strpos($name, '/')) {
  944. list($name, $type) = explode('/', $name);
  945. } else {
  946. $type = 's';
  947. }
  948. // 按.拆分成多维数组进行判断
  949. foreach (explode('.', $name) as $val) {
  950. if (isset($data[$val])) {
  951. $data = $data[$val];
  952. } else {
  953. // 无输入数据,返回默认值
  954. return $default;
  955. }
  956. }
  957. if (is_object($data)) {
  958. return $data;
  959. }
  960. }
  961. // 解析过滤器
  962. $filter = $this->getFilter($filter, $default);
  963. if (is_array($data)) {
  964. array_walk_recursive($data, [$this, 'filterValue'], $filter);
  965. reset($data);
  966. } else {
  967. $this->filterValue($data, $name, $filter);
  968. }
  969. if (isset($type) && $data !== $default) {
  970. // 强制类型转换
  971. $this->typeCast($data, $type);
  972. }
  973. return $data;
  974. }
  975. /**
  976. * 设置或获取当前的过滤规则
  977. * @param mixed $filter 过滤规则
  978. * @return mixed
  979. */
  980. public function filter($filter = null)
  981. {
  982. if (is_null($filter)) {
  983. return $this->filter;
  984. } else {
  985. $this->filter = $filter;
  986. }
  987. }
  988. protected function getFilter($filter, $default)
  989. {
  990. if (is_null($filter)) {
  991. $filter = [];
  992. } else {
  993. $filter = $filter ?: $this->filter;
  994. if (is_string($filter) && false === strpos($filter, '/')) {
  995. $filter = explode(',', $filter);
  996. } else {
  997. $filter = (array) $filter;
  998. }
  999. }
  1000. $filter[] = $default;
  1001. return $filter;
  1002. }
  1003. /**
  1004. * 递归过滤给定的值
  1005. * @param mixed $value 键值
  1006. * @param mixed $key 键名
  1007. * @param array $filters 过滤方法+默认值
  1008. * @return mixed
  1009. */
  1010. private function filterValue(&$value, $key, $filters)
  1011. {
  1012. $default = array_pop($filters);
  1013. foreach ($filters as $filter) {
  1014. if (is_callable($filter)) {
  1015. // 调用函数或者方法过滤
  1016. $value = call_user_func($filter, $value);
  1017. } elseif (is_scalar($value)) {
  1018. if (false !== strpos($filter, '/')) {
  1019. // 正则过滤
  1020. if (!preg_match($filter, $value)) {
  1021. // 匹配不成功返回默认值
  1022. $value = $default;
  1023. break;
  1024. }
  1025. } elseif (!empty($filter)) {
  1026. // filter函数不存在时, 则使用filter_var进行过滤
  1027. // filter为非整形值时, 调用filter_id取得过滤id
  1028. $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
  1029. if (false === $value) {
  1030. $value = $default;
  1031. break;
  1032. }
  1033. }
  1034. }
  1035. }
  1036. return $this->filterExp($value);
  1037. }
  1038. /**
  1039. * 过滤表单中的表达式
  1040. * @param string $value
  1041. * @return void
  1042. */
  1043. public function filterExp(&$value)
  1044. {
  1045. // 过滤查询特殊字符
  1046. if (is_string($value) && preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT LIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOT EXISTS|NOTEXISTS|EXISTS|NOT NULL|NOTNULL|NULL|BETWEEN TIME|NOT BETWEEN TIME|NOTBETWEEN TIME|NOTIN|NOT IN|IN)$/i', $value)) {
  1047. $value .= ' ';
  1048. }
  1049. // TODO 其他安全过滤
  1050. }
  1051. /**
  1052. * 强制类型转换
  1053. * @param string $data
  1054. * @param string $type
  1055. * @return mixed
  1056. */
  1057. private function typeCast(&$data, $type)
  1058. {
  1059. switch (strtolower($type)) {
  1060. // 数组
  1061. case 'a':
  1062. $data = (array) $data;
  1063. break;
  1064. // 数字
  1065. case 'd':
  1066. $data = (int) $data;
  1067. break;
  1068. // 浮点
  1069. case 'f':
  1070. $data = (float) $data;
  1071. break;
  1072. // 布尔
  1073. case 'b':
  1074. $data = (boolean) $data;
  1075. break;
  1076. // 字符串
  1077. case 's':
  1078. default:
  1079. if (is_scalar($data)) {
  1080. $data = (string) $data;
  1081. } else {
  1082. throw new \InvalidArgumentException('variable type error:' . gettype($data));
  1083. }
  1084. }
  1085. }
  1086. /**
  1087. * 是否存在某个请求参数
  1088. * @access public
  1089. * @param string $name 变量名
  1090. * @param string $type 变量类型
  1091. * @param bool $checkEmpty 是否检测空值
  1092. * @return mixed
  1093. */
  1094. public function has($name, $type = 'param', $checkEmpty = false)
  1095. {
  1096. if (empty($this->$type)) {
  1097. $param = $this->$type();
  1098. } else {
  1099. $param = $this->$type;
  1100. }
  1101. // 按.拆分成多维数组进行判断
  1102. foreach (explode('.', $name) as $val) {
  1103. if (isset($param[$val])) {
  1104. $param = $param[$val];
  1105. } else {
  1106. return false;
  1107. }
  1108. }
  1109. return ($checkEmpty && '' === $param) ? false : true;
  1110. }
  1111. /**
  1112. * 获取指定的参数
  1113. * @access public
  1114. * @param string|array $name 变量名
  1115. * @param string $type 变量类型
  1116. * @return mixed
  1117. */
  1118. public function only($name, $type = 'param')
  1119. {
  1120. $param = $this->$type();
  1121. if (is_string($name)) {
  1122. $name = explode(',', $name);
  1123. }
  1124. $item = [];
  1125. foreach ($name as $key) {
  1126. if (isset($param[$key])) {
  1127. $item[$key] = $param[$key];
  1128. }
  1129. }
  1130. return $item;
  1131. }
  1132. /**
  1133. * 排除指定参数获取
  1134. * @access public
  1135. * @param string|array $name 变量名
  1136. * @param string $type 变量类型
  1137. * @return mixed
  1138. */
  1139. public function except($name, $type = 'param')
  1140. {
  1141. $param = $this->$type();
  1142. if (is_string($name)) {
  1143. $name = explode(',', $name);
  1144. }
  1145. foreach ($name as $key) {
  1146. if (isset($param[$key])) {
  1147. unset($param[$key]);
  1148. }
  1149. }
  1150. return $param;
  1151. }
  1152. /**
  1153. * 当前是否ssl
  1154. * @access public
  1155. * @return bool
  1156. */
  1157. public function isSsl()
  1158. {
  1159. $server = array_merge($_SERVER, $this->server);
  1160. if (isset($server['HTTPS']) && ('1' == $server['HTTPS'] || 'on' == strtolower($server['HTTPS']))) {
  1161. return true;
  1162. } elseif (isset($server['REQUEST_SCHEME']) && 'https' == $server['REQUEST_SCHEME']) {
  1163. return true;
  1164. } elseif (isset($server['SERVER_PORT']) && ('443' == $server['SERVER_PORT'])) {
  1165. return true;
  1166. } elseif (isset($server['HTTP_X_FORWARDED_PROTO']) && 'https' == $server['HTTP_X_FORWARDED_PROTO']) {
  1167. return true;
  1168. } elseif (Config::get('https_agent_name') && isset($server[Config::get('https_agent_name')])) {
  1169. return true;
  1170. }
  1171. return false;
  1172. }
  1173. /**
  1174. * 当前是否Ajax请求
  1175. * @access public
  1176. * @param bool $ajax true 获取原始ajax请求
  1177. * @return bool
  1178. */
  1179. public function isAjax($ajax = false)
  1180. {
  1181. $value = $this->server('HTTP_X_REQUESTED_WITH', '', 'strtolower');
  1182. $result = ('xmlhttprequest' == $value) ? true : false;
  1183. if (true === $ajax) {
  1184. return $result;
  1185. } else {
  1186. $result = $this->param(Config::get('var_ajax')) ? true : $result;
  1187. $this->mergeParam = false;
  1188. return $result;
  1189. }
  1190. }
  1191. /**
  1192. * 当前是否Pjax请求
  1193. * @access public
  1194. * @param bool $pjax true 获取原始pjax请求
  1195. * @return bool
  1196. */
  1197. public function isPjax($pjax = false)
  1198. {
  1199. $result = !is_null($this->server('HTTP_X_PJAX')) ? true : false;
  1200. if (true === $pjax) {
  1201. return $result;
  1202. } else {
  1203. $result = $this->param(Config::get('var_pjax')) ? true : $result;
  1204. $this->mergeParam = false;
  1205. return $result;
  1206. }
  1207. }
  1208. /**
  1209. * 获取客户端IP地址
  1210. * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
  1211. * @param boolean $adv 是否进行高级模式获取(有可能被伪装)
  1212. * @return mixed
  1213. */
  1214. public function ip($type = 0, $adv = true)
  1215. {
  1216. $type = $type ? 1 : 0;
  1217. static $ip = null;
  1218. if (null !== $ip) {
  1219. return $ip[$type];
  1220. }
  1221. $httpAgentIp = Config::get('http_agent_ip');
  1222. if ($httpAgentIp && isset($_SERVER[$httpAgentIp])) {
  1223. $ip = $_SERVER[$httpAgentIp];
  1224. } elseif ($adv) {
  1225. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1226. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1227. $pos = array_search('unknown', $arr);
  1228. if (false !== $pos) {
  1229. unset($arr[$pos]);
  1230. }
  1231. $ip = trim(current($arr));
  1232. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1233. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1234. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1235. $ip = $_SERVER['REMOTE_ADDR'];
  1236. }
  1237. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1238. $ip = $_SERVER['REMOTE_ADDR'];
  1239. }
  1240. // IP地址合法验证
  1241. $long = sprintf("%u", ip2long($ip));
  1242. $ip = $long ? [$ip, $long] : ['0.0.0.0', 0];
  1243. return $ip[$type];
  1244. }
  1245. /**
  1246. * 检测是否使用手机访问
  1247. * @access public
  1248. * @return bool
  1249. */
  1250. public function isMobile()
  1251. {
  1252. if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) {
  1253. return true;
  1254. } elseif (isset($_SERVER['HTTP_ACCEPT']) && strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML")) {
  1255. return true;
  1256. } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {
  1257. return true;
  1258. } elseif (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])) {
  1259. return true;
  1260. } else {
  1261. return false;
  1262. }
  1263. }
  1264. /**
  1265. * 当前URL地址中的scheme参数
  1266. * @access public
  1267. * @return string
  1268. */
  1269. public function scheme()
  1270. {
  1271. return $this->isSsl() ? 'https' : 'http';
  1272. }
  1273. /**
  1274. * 当前请求URL地址中的query参数
  1275. * @access public
  1276. * @return string
  1277. */
  1278. public function query()
  1279. {
  1280. return $this->server('QUERY_STRING');
  1281. }
  1282. /**
  1283. * 当前请求的host
  1284. * @access public
  1285. * @param bool $strict true 仅仅获取HOST
  1286. * @return string
  1287. */
  1288. public function host($strict = false)
  1289. {
  1290. if (isset($_SERVER['HTTP_X_REAL_HOST'])) {
  1291. $host = $_SERVER['HTTP_X_REAL_HOST'];
  1292. } else {
  1293. $host = $this->server('HTTP_HOST');
  1294. }
  1295. return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
  1296. }
  1297. /**
  1298. * 当前请求URL地址中的port参数
  1299. * @access public
  1300. * @return integer
  1301. */
  1302. public function port()
  1303. {
  1304. return $this->server('SERVER_PORT');
  1305. }
  1306. /**
  1307. * 当前请求 SERVER_PROTOCOL
  1308. * @access public
  1309. * @return integer
  1310. */
  1311. public function protocol()
  1312. {
  1313. return $this->server('SERVER_PROTOCOL');
  1314. }
  1315. /**
  1316. * 当前请求 REMOTE_PORT
  1317. * @access public
  1318. * @return integer
  1319. */
  1320. public function remotePort()
  1321. {
  1322. return $this->server('REMOTE_PORT');
  1323. }
  1324. /**
  1325. * 当前请求 HTTP_CONTENT_TYPE
  1326. * @access public
  1327. * @return string
  1328. */
  1329. public function contentType()
  1330. {
  1331. $contentType = $this->server('CONTENT_TYPE');
  1332. if ($contentType) {
  1333. if (strpos($contentType, ';')) {
  1334. list($type) = explode(';', $contentType);
  1335. } else {
  1336. $type = $contentType;
  1337. }
  1338. return trim($type);
  1339. }
  1340. return '';
  1341. }
  1342. /**
  1343. * 获取当前请求的路由信息
  1344. * @access public
  1345. * @param array $route 路由名称
  1346. * @return array
  1347. */
  1348. public function routeInfo($route = [])
  1349. {
  1350. if (!empty($route)) {
  1351. $this->routeInfo = $route;
  1352. } else {
  1353. return $this->routeInfo;
  1354. }
  1355. }
  1356. /**
  1357. * 设置或者获取当前请求的调度信息
  1358. * @access public
  1359. * @param array $dispatch 调度信息
  1360. * @return array
  1361. */
  1362. public function dispatch($dispatch = null)
  1363. {
  1364. if (!is_null($dispatch)) {
  1365. $this->dispatch = $dispatch;
  1366. }
  1367. return $this->dispatch;
  1368. }
  1369. /**
  1370. * 设置或者获取当前的模块名
  1371. * @access public
  1372. * @param string $module 模块名
  1373. * @return string|Request
  1374. */
  1375. public function module($module = null)
  1376. {
  1377. if (!is_null($module)) {
  1378. $this->module = $module;
  1379. return $this;
  1380. } else {
  1381. return $this->module ?: '';
  1382. }
  1383. }
  1384. /**
  1385. * 设置或者获取当前的控制器名
  1386. * @access public
  1387. * @param string $controller 控制器名
  1388. * @return string|Request
  1389. */
  1390. public function controller($controller = null)
  1391. {
  1392. if (!is_null($controller)) {
  1393. $this->controller = $controller;
  1394. return $this;
  1395. } else {
  1396. return $this->controller ?: '';
  1397. }
  1398. }
  1399. /**
  1400. * 设置或者获取当前的操作名
  1401. * @access public
  1402. * @param string $action 操作名
  1403. * @return string|Request
  1404. */
  1405. public function action($action = null)
  1406. {
  1407. if (!is_null($action) && !is_bool($action)) {
  1408. $this->action = $action;
  1409. return $this;
  1410. } else {
  1411. $name = $this->action ?: '';
  1412. return true === $action ? $name : strtolower($name);
  1413. }
  1414. }
  1415. /**
  1416. * 设置或者获取当前的语言
  1417. * @access public
  1418. * @param string $lang 语言名
  1419. * @return string|Request
  1420. */
  1421. public function langset($lang = null)
  1422. {
  1423. if (!is_null($lang)) {
  1424. $this->langset = $lang;
  1425. return $this;
  1426. } else {
  1427. return $this->langset ?: '';
  1428. }
  1429. }
  1430. /**
  1431. * 设置或者获取当前请求的content
  1432. * @access public
  1433. * @return string
  1434. */
  1435. public function getContent()
  1436. {
  1437. if (is_null($this->content)) {
  1438. $this->content = $this->input;
  1439. }
  1440. return $this->content;
  1441. }
  1442. /**
  1443. * 获取当前请求的php://input
  1444. * @access public
  1445. * @return string
  1446. */
  1447. public function getInput()
  1448. {
  1449. return $this->input;
  1450. }
  1451. /**
  1452. * 生成请求令牌
  1453. * @access public
  1454. * @param string $name 令牌名称
  1455. * @param mixed $type 令牌生成方法
  1456. * @return string
  1457. */
  1458. public function token($name = '__token__', $type = 'md5')
  1459. {
  1460. $type = is_callable($type) ? $type : 'md5';
  1461. $token = call_user_func($type, $_SERVER['REQUEST_TIME_FLOAT']);
  1462. if ($this->isAjax()) {
  1463. header($name . ': ' . $token);
  1464. }
  1465. Session::set($name, $token);
  1466. return $token;
  1467. }
  1468. /**
  1469. * 设置当前地址的请求缓存
  1470. * @access public
  1471. * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id
  1472. * @param mixed $expire 缓存有效期
  1473. * @param array $except 缓存排除
  1474. * @param string $tag 缓存标签
  1475. * @return void
  1476. */
  1477. public function cache($key, $expire = null, $except = [], $tag = null)
  1478. {
  1479. if (!is_array($except)) {
  1480. $tag = $except;
  1481. $except = [];
  1482. }
  1483. if (false !== $key && $this->isGet() && !$this->isCheckCache) {
  1484. // 标记请求缓存检查
  1485. $this->isCheckCache = true;
  1486. if (false === $expire) {
  1487. // 关闭当前缓存
  1488. return;
  1489. }
  1490. if ($key instanceof \Closure) {
  1491. $key = call_user_func_array($key, [$this]);
  1492. } elseif (true === $key) {
  1493. foreach ($except as $rule) {
  1494. if (0 === stripos($this->url(), $rule)) {
  1495. return;
  1496. }
  1497. }
  1498. // 自动缓存功能
  1499. $key = '__URL__';
  1500. } elseif (strpos($key, '|')) {
  1501. list($key, $fun) = explode('|', $key);
  1502. }
  1503. // 特殊规则替换
  1504. if (false !== strpos($key, '__')) {
  1505. $key = str_replace(['__MODULE__', '__CONTROLLER__', '__ACTION__', '__URL__', ''], [$this->module, $this->controller, $this->action, md5($this->url(true))], $key);
  1506. }
  1507. if (false !== strpos($key, ':')) {
  1508. $param = $this->param();
  1509. foreach ($param as $item => $val) {
  1510. if (is_string($val) && false !== strpos($key, ':' . $item)) {
  1511. $key = str_replace(':' . $item, $val, $key);
  1512. }
  1513. }
  1514. } elseif (strpos($key, ']')) {
  1515. if ('[' . $this->ext() . ']' == $key) {
  1516. // 缓存某个后缀的请求
  1517. $key = md5($this->url());
  1518. } else {
  1519. return;
  1520. }
  1521. }
  1522. if (isset($fun)) {
  1523. $key = $fun($key);
  1524. }
  1525. if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) {
  1526. // 读取缓存
  1527. $response = Response::create()->code(304);
  1528. throw new \think\exception\HttpResponseException($response);
  1529. } elseif (Cache::has($key)) {
  1530. list($content, $header) = Cache::get($key);
  1531. $response = Response::create($content)->header($header);
  1532. throw new \think\exception\HttpResponseException($response);
  1533. } else {
  1534. $this->cache = [$key, $expire, $tag];
  1535. }
  1536. }
  1537. }
  1538. /**
  1539. * 读取请求缓存设置
  1540. * @access public
  1541. * @return array
  1542. */
  1543. public function getCache()
  1544. {
  1545. return $this->cache;
  1546. }
  1547. /**
  1548. * 设置当前请求绑定的对象实例
  1549. * @access public
  1550. * @param string|array $name 绑定的对象标识
  1551. * @param mixed $obj 绑定的对象实例
  1552. * @return mixed
  1553. */
  1554. public function bind($name, $obj = null)
  1555. {
  1556. if (is_array($name)) {
  1557. $this->bind = array_merge($this->bind, $name);
  1558. } else {
  1559. $this->bind[$name] = $obj;
  1560. }
  1561. }
  1562. public function __set($name, $value)
  1563. {
  1564. $this->bind[$name] = $value;
  1565. }
  1566. public function __get($name)
  1567. {
  1568. return isset($this->bind[$name]) ? $this->bind[$name] : null;
  1569. }
  1570. public function __isset($name)
  1571. {
  1572. return isset($this->bind[$name]);
  1573. }
  1574. }