Request.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  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. $varMethod = Config::get('var_method');
  487. if ($varMethod && isset($_POST[$varMethod])) {
  488. $method = strtoupper($_POST[$varMethod]);
  489. if (in_array($method, ['GET', 'POST', 'DELETE', 'PUT', 'PATCH'])) {
  490. $this->method = $method;
  491. $this->{$this->method}($_POST);
  492. } else {
  493. $this->method = 'POST';
  494. }
  495. unset($_POST[$varMethod]);
  496. } else {
  497. $method = $this->server('REQUEST_METHOD') ?: 'GET';
  498. $httpMethodOverride = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ?? '');
  499. if ($method === 'POST' && in_array($httpMethodOverride, ['GET', 'POST', 'DELETE', 'PUT', 'PATCH'])) {
  500. $this->method = $httpMethodOverride;
  501. } else {
  502. $this->method = $method;
  503. }
  504. }
  505. }
  506. return $this->method;
  507. }
  508. /**
  509. * 是否为GET请求
  510. * @access public
  511. * @return bool
  512. */
  513. public function isGet()
  514. {
  515. return $this->method() == 'GET';
  516. }
  517. /**
  518. * 是否为POST请求
  519. * @access public
  520. * @return bool
  521. */
  522. public function isPost()
  523. {
  524. return $this->method() == 'POST';
  525. }
  526. /**
  527. * 是否为PUT请求
  528. * @access public
  529. * @return bool
  530. */
  531. public function isPut()
  532. {
  533. return $this->method() == 'PUT';
  534. }
  535. /**
  536. * 是否为DELTE请求
  537. * @access public
  538. * @return bool
  539. */
  540. public function isDelete()
  541. {
  542. return $this->method() == 'DELETE';
  543. }
  544. /**
  545. * 是否为HEAD请求
  546. * @access public
  547. * @return bool
  548. */
  549. public function isHead()
  550. {
  551. return $this->method() == 'HEAD';
  552. }
  553. /**
  554. * 是否为PATCH请求
  555. * @access public
  556. * @return bool
  557. */
  558. public function isPatch()
  559. {
  560. return $this->method() == 'PATCH';
  561. }
  562. /**
  563. * 是否为OPTIONS请求
  564. * @access public
  565. * @return bool
  566. */
  567. public function isOptions()
  568. {
  569. return $this->method() == 'OPTIONS';
  570. }
  571. /**
  572. * 是否为cli
  573. * @access public
  574. * @return bool
  575. */
  576. public function isCli()
  577. {
  578. return PHP_SAPI == 'cli';
  579. }
  580. /**
  581. * 是否为cgi
  582. * @access public
  583. * @return bool
  584. */
  585. public function isCgi()
  586. {
  587. return strpos(PHP_SAPI, 'cgi') === 0;
  588. }
  589. /**
  590. * 获取当前请求的参数
  591. * @access public
  592. * @param string|array $name 变量名
  593. * @param mixed $default 默认值
  594. * @param string|array $filter 过滤方法
  595. * @return mixed
  596. */
  597. public function param($name = '', $default = null, $filter = '')
  598. {
  599. if (empty($this->mergeParam)) {
  600. $method = $this->method(true);
  601. // 自动获取请求变量
  602. switch ($method) {
  603. case 'POST':
  604. $vars = $this->post(false);
  605. break;
  606. case 'PUT':
  607. case 'DELETE':
  608. case 'PATCH':
  609. $vars = $this->put(false);
  610. break;
  611. default:
  612. $vars = [];
  613. }
  614. // 当前请求参数和URL地址中的参数合并
  615. $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
  616. $this->mergeParam = true;
  617. }
  618. if (true === $name) {
  619. // 获取包含文件上传信息的数组
  620. $file = $this->file();
  621. $data = is_array($file) ? array_merge($this->param, $file) : $this->param;
  622. return $this->input($data, '', $default, $filter);
  623. }
  624. return $this->input($this->param, $name, $default, $filter);
  625. }
  626. /**
  627. * 设置获取路由参数
  628. * @access public
  629. * @param string|array $name 变量名
  630. * @param mixed $default 默认值
  631. * @param string|array $filter 过滤方法
  632. * @return mixed
  633. */
  634. public function route($name = '', $default = null, $filter = '')
  635. {
  636. if (is_array($name)) {
  637. $this->param = [];
  638. $this->mergeParam = false;
  639. return $this->route = array_merge($this->route, $name);
  640. }
  641. return $this->input($this->route, $name, $default, $filter);
  642. }
  643. /**
  644. * 设置获取GET参数
  645. * @access public
  646. * @param string|array $name 变量名
  647. * @param mixed $default 默认值
  648. * @param string|array $filter 过滤方法
  649. * @return mixed
  650. */
  651. public function get($name = '', $default = null, $filter = '')
  652. {
  653. if (empty($this->get)) {
  654. $this->get = $_GET;
  655. }
  656. if (is_array($name)) {
  657. $this->param = [];
  658. $this->mergeParam = false;
  659. return $this->get = array_merge($this->get, $name);
  660. }
  661. return $this->input($this->get, $name, $default, $filter);
  662. }
  663. /**
  664. * 设置获取POST参数
  665. * @access public
  666. * @param string $name 变量名
  667. * @param mixed $default 默认值
  668. * @param string|array $filter 过滤方法
  669. * @return mixed
  670. */
  671. public function post($name = '', $default = null, $filter = '')
  672. {
  673. if (empty($this->post)) {
  674. $content = $this->input;
  675. if (empty($_POST) && false !== strpos($this->contentType(), 'application/json')) {
  676. $this->post = (array) json_decode($content, true);
  677. } else {
  678. $this->post = $_POST;
  679. }
  680. }
  681. if (is_array($name)) {
  682. $this->param = [];
  683. $this->mergeParam = false;
  684. return $this->post = array_merge($this->post, $name);
  685. }
  686. return $this->input($this->post, $name, $default, $filter);
  687. }
  688. /**
  689. * 设置获取PUT参数
  690. * @access public
  691. * @param string|array $name 变量名
  692. * @param mixed $default 默认值
  693. * @param string|array $filter 过滤方法
  694. * @return mixed
  695. */
  696. public function put($name = '', $default = null, $filter = '')
  697. {
  698. if (is_null($this->put)) {
  699. $content = $this->input;
  700. if (false !== strpos($this->contentType(), 'application/json')) {
  701. $this->put = (array) json_decode($content, true);
  702. } else {
  703. parse_str($content, $this->put);
  704. }
  705. }
  706. if (is_array($name)) {
  707. $this->param = [];
  708. $this->mergeParam = false;
  709. return $this->put = is_null($this->put) ? $name : array_merge($this->put, $name);
  710. }
  711. return $this->input($this->put, $name, $default, $filter);
  712. }
  713. /**
  714. * 设置获取DELETE参数
  715. * @access public
  716. * @param string|array $name 变量名
  717. * @param mixed $default 默认值
  718. * @param string|array $filter 过滤方法
  719. * @return mixed
  720. */
  721. public function delete($name = '', $default = null, $filter = '')
  722. {
  723. return $this->put($name, $default, $filter);
  724. }
  725. /**
  726. * 设置获取PATCH参数
  727. * @access public
  728. * @param string|array $name 变量名
  729. * @param mixed $default 默认值
  730. * @param string|array $filter 过滤方法
  731. * @return mixed
  732. */
  733. public function patch($name = '', $default = null, $filter = '')
  734. {
  735. return $this->put($name, $default, $filter);
  736. }
  737. /**
  738. * 获取request变量
  739. * @param string $name 数据名称
  740. * @param string $default 默认值
  741. * @param string|array $filter 过滤方法
  742. * @return mixed
  743. */
  744. public function request($name = '', $default = null, $filter = '')
  745. {
  746. if (empty($this->request)) {
  747. $this->request = $_REQUEST;
  748. }
  749. if (is_array($name)) {
  750. $this->param = [];
  751. $this->mergeParam = false;
  752. return $this->request = array_merge($this->request, $name);
  753. }
  754. return $this->input($this->request, $name, $default, $filter);
  755. }
  756. /**
  757. * 获取session数据
  758. * @access public
  759. * @param string|array $name 数据名称
  760. * @param string $default 默认值
  761. * @param string|array $filter 过滤方法
  762. * @return mixed
  763. */
  764. public function session($name = '', $default = null, $filter = '')
  765. {
  766. if (empty($this->session)) {
  767. $this->session = Session::get();
  768. }
  769. if (is_array($name)) {
  770. return $this->session = array_merge($this->session, $name);
  771. }
  772. return $this->input($this->session, $name, $default, $filter);
  773. }
  774. /**
  775. * 获取cookie参数
  776. * @access public
  777. * @param string|array $name 数据名称
  778. * @param string $default 默认值
  779. * @param string|array $filter 过滤方法
  780. * @return mixed
  781. */
  782. public function cookie($name = '', $default = null, $filter = '')
  783. {
  784. if (empty($this->cookie)) {
  785. $this->cookie = Cookie::get();
  786. }
  787. if (is_array($name)) {
  788. return $this->cookie = array_merge($this->cookie, $name);
  789. } elseif (!empty($name)) {
  790. $data = Cookie::has($name) ? Cookie::get($name) : $default;
  791. } else {
  792. $data = $this->cookie;
  793. }
  794. // 解析过滤器
  795. $filter = $this->getFilter($filter, $default);
  796. if (is_array($data)) {
  797. array_walk_recursive($data, [$this, 'filterValue'], $filter);
  798. reset($data);
  799. } else {
  800. $this->filterValue($data, $name, $filter);
  801. }
  802. return $data;
  803. }
  804. /**
  805. * 获取server参数
  806. * @access public
  807. * @param string|array $name 数据名称
  808. * @param string $default 默认值
  809. * @param string|array $filter 过滤方法
  810. * @return mixed
  811. */
  812. public function server($name = '', $default = null, $filter = '')
  813. {
  814. if (empty($this->server)) {
  815. $this->server = $_SERVER;
  816. }
  817. if (is_array($name)) {
  818. return $this->server = array_merge($this->server, $name);
  819. }
  820. return $this->input($this->server, false === $name ? false : strtoupper($name), $default, $filter);
  821. }
  822. /**
  823. * 获取上传的文件信息
  824. * @access public
  825. * @param string|array $name 名称
  826. * @return null|array|\think\File
  827. */
  828. public function file($name = '')
  829. {
  830. if (empty($this->file)) {
  831. $this->file = isset($_FILES) ? $_FILES : [];
  832. }
  833. if (is_array($name)) {
  834. return $this->file = array_merge($this->file, $name);
  835. }
  836. $files = $this->file;
  837. if (!empty($files)) {
  838. // 处理上传文件
  839. $array = [];
  840. foreach ($files as $key => $file) {
  841. if (is_array($file['name'])) {
  842. $item = [];
  843. $keys = array_keys($file);
  844. $count = count($file['name']);
  845. for ($i = 0; $i < $count; $i++) {
  846. if (empty($file['tmp_name'][$i]) || !is_file($file['tmp_name'][$i])) {
  847. continue;
  848. }
  849. $temp['key'] = $key;
  850. foreach ($keys as $_key) {
  851. $temp[$_key] = $file[$_key][$i];
  852. }
  853. $item[] = (new File($temp['tmp_name']))->setUploadInfo($temp);
  854. }
  855. $array[$key] = $item;
  856. } else {
  857. if ($file instanceof File) {
  858. $array[$key] = $file;
  859. } else {
  860. if (empty($file['tmp_name']) || !is_file($file['tmp_name'])) {
  861. continue;
  862. }
  863. $array[$key] = (new File($file['tmp_name']))->setUploadInfo($file);
  864. }
  865. }
  866. }
  867. if (strpos($name, '.')) {
  868. list($name, $sub) = explode('.', $name);
  869. }
  870. if ('' === $name) {
  871. // 获取全部文件
  872. return $array;
  873. } elseif (isset($sub) && isset($array[$name][$sub])) {
  874. return $array[$name][$sub];
  875. } elseif (isset($array[$name])) {
  876. return $array[$name];
  877. }
  878. }
  879. return;
  880. }
  881. /**
  882. * 获取环境变量
  883. * @param string|array $name 数据名称
  884. * @param string $default 默认值
  885. * @param string|array $filter 过滤方法
  886. * @return mixed
  887. */
  888. public function env($name = '', $default = null, $filter = '')
  889. {
  890. if (empty($this->env)) {
  891. $this->env = $_ENV;
  892. }
  893. if (is_array($name)) {
  894. return $this->env = array_merge($this->env, $name);
  895. }
  896. return $this->input($this->env, false === $name ? false : strtoupper($name), $default, $filter);
  897. }
  898. /**
  899. * 设置或者获取当前的Header
  900. * @access public
  901. * @param string|array $name header名称
  902. * @param string $default 默认值
  903. * @return string
  904. */
  905. public function header($name = '', $default = null)
  906. {
  907. if (empty($this->header)) {
  908. $header = [];
  909. if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
  910. $header = $result;
  911. } else {
  912. $server = $this->server ?: $_SERVER;
  913. foreach ($server as $key => $val) {
  914. if (0 === strpos($key, 'HTTP_')) {
  915. $key = str_replace('_', '-', strtolower(substr($key, 5)));
  916. $header[$key] = $val;
  917. }
  918. }
  919. if (isset($server['CONTENT_TYPE'])) {
  920. $header['content-type'] = $server['CONTENT_TYPE'];
  921. }
  922. if (isset($server['CONTENT_LENGTH'])) {
  923. $header['content-length'] = $server['CONTENT_LENGTH'];
  924. }
  925. }
  926. $this->header = array_change_key_case($header);
  927. }
  928. if (is_array($name)) {
  929. return $this->header = array_merge($this->header, $name);
  930. }
  931. if ('' === $name) {
  932. return $this->header;
  933. }
  934. $name = str_replace('_', '-', strtolower($name));
  935. return isset($this->header[$name]) ? $this->header[$name] : $default;
  936. }
  937. /**
  938. * 获取变量 支持过滤和默认值
  939. * @param array $data 数据源
  940. * @param string|false $name 字段名
  941. * @param mixed $default 默认值
  942. * @param string|array $filter 过滤函数
  943. * @return mixed
  944. */
  945. public function input($data = [], $name = '', $default = null, $filter = '')
  946. {
  947. if (false === $name) {
  948. // 获取原始数据
  949. return $data;
  950. }
  951. $name = (string) $name;
  952. if ('' != $name) {
  953. // 解析name
  954. if (strpos($name, '/')) {
  955. list($name, $type) = explode('/', $name);
  956. } else {
  957. $type = 's';
  958. }
  959. // 按.拆分成多维数组进行判断
  960. foreach (explode('.', $name) as $val) {
  961. if (isset($data[$val])) {
  962. $data = $data[$val];
  963. } else {
  964. // 无输入数据,返回默认值
  965. return $default;
  966. }
  967. }
  968. if (is_object($data)) {
  969. return $data;
  970. }
  971. }
  972. // 解析过滤器
  973. $filter = $this->getFilter($filter, $default);
  974. if (is_array($data)) {
  975. array_walk_recursive($data, [$this, 'filterValue'], $filter);
  976. reset($data);
  977. } else {
  978. $this->filterValue($data, $name, $filter);
  979. }
  980. if (isset($type) && $data !== $default) {
  981. // 强制类型转换
  982. $this->typeCast($data, $type);
  983. }
  984. return $data;
  985. }
  986. /**
  987. * 设置或获取当前的过滤规则
  988. * @param mixed $filter 过滤规则
  989. * @return mixed
  990. */
  991. public function filter($filter = null)
  992. {
  993. if (is_null($filter)) {
  994. return $this->filter;
  995. } else {
  996. $this->filter = $filter;
  997. }
  998. }
  999. protected function getFilter($filter, $default)
  1000. {
  1001. if (is_null($filter)) {
  1002. $filter = [];
  1003. } else {
  1004. $filter = $filter ?: $this->filter;
  1005. if (is_string($filter) && false === strpos($filter, '/')) {
  1006. $filter = explode(',', $filter);
  1007. } else {
  1008. $filter = (array) $filter;
  1009. }
  1010. }
  1011. $filter[] = $default;
  1012. return $filter;
  1013. }
  1014. /**
  1015. * 递归过滤给定的值
  1016. * @param mixed $value 键值
  1017. * @param mixed $key 键名
  1018. * @param array $filters 过滤方法+默认值
  1019. * @return mixed
  1020. */
  1021. private function filterValue(&$value, $key, $filters)
  1022. {
  1023. $default = array_pop($filters);
  1024. foreach ($filters as $filter) {
  1025. if (is_callable($filter)) {
  1026. // 调用函数或者方法过滤
  1027. $value = call_user_func($filter, $value ?? '');
  1028. } elseif (is_scalar($value)) {
  1029. if (false !== strpos($filter, '/')) {
  1030. // 正则过滤
  1031. if (!preg_match($filter, $value)) {
  1032. // 匹配不成功返回默认值
  1033. $value = $default;
  1034. break;
  1035. }
  1036. } elseif (!empty($filter)) {
  1037. // filter函数不存在时, 则使用filter_var进行过滤
  1038. // filter为非整形值时, 调用filter_id取得过滤id
  1039. $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
  1040. if (false === $value) {
  1041. $value = $default;
  1042. break;
  1043. }
  1044. }
  1045. }
  1046. }
  1047. return $this->filterExp($value);
  1048. }
  1049. /**
  1050. * 过滤表单中的表达式
  1051. * @param string $value
  1052. * @return void
  1053. */
  1054. public function filterExp(&$value)
  1055. {
  1056. // 过滤查询特殊字符
  1057. 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)) {
  1058. $value .= ' ';
  1059. }
  1060. // TODO 其他安全过滤
  1061. }
  1062. /**
  1063. * 强制类型转换
  1064. * @param string $data
  1065. * @param string $type
  1066. * @return mixed
  1067. */
  1068. private function typeCast(&$data, $type)
  1069. {
  1070. switch (strtolower($type)) {
  1071. // 数组
  1072. case 'a':
  1073. $data = (array) $data;
  1074. break;
  1075. // 数字
  1076. case 'd':
  1077. $data = (int) $data;
  1078. break;
  1079. // 浮点
  1080. case 'f':
  1081. $data = (float) $data;
  1082. break;
  1083. // 布尔
  1084. case 'b':
  1085. $data = (boolean) $data;
  1086. break;
  1087. // 字符串
  1088. case 's':
  1089. default:
  1090. if (is_scalar($data)) {
  1091. $data = (string) $data;
  1092. } else {
  1093. throw new \InvalidArgumentException('variable type error:' . gettype($data));
  1094. }
  1095. }
  1096. }
  1097. /**
  1098. * 是否存在某个请求参数
  1099. * @access public
  1100. * @param string $name 变量名
  1101. * @param string $type 变量类型
  1102. * @param bool $checkEmpty 是否检测空值
  1103. * @return mixed
  1104. */
  1105. public function has($name, $type = 'param', $checkEmpty = false)
  1106. {
  1107. if (empty($this->$type)) {
  1108. $param = $this->$type();
  1109. } else {
  1110. $param = $this->$type;
  1111. }
  1112. // 按.拆分成多维数组进行判断
  1113. foreach (explode('.', $name) as $val) {
  1114. if (isset($param[$val])) {
  1115. $param = $param[$val];
  1116. } else {
  1117. return false;
  1118. }
  1119. }
  1120. return ($checkEmpty && '' === $param) ? false : true;
  1121. }
  1122. /**
  1123. * 获取指定的参数
  1124. * @access public
  1125. * @param string|array $name 变量名
  1126. * @param string $type 变量类型
  1127. * @return mixed
  1128. */
  1129. public function only($name, $type = 'param')
  1130. {
  1131. $param = $this->$type();
  1132. if (is_string($name)) {
  1133. $name = explode(',', $name);
  1134. }
  1135. $item = [];
  1136. foreach ($name as $key) {
  1137. if (isset($param[$key])) {
  1138. $item[$key] = $param[$key];
  1139. }
  1140. }
  1141. return $item;
  1142. }
  1143. /**
  1144. * 排除指定参数获取
  1145. * @access public
  1146. * @param string|array $name 变量名
  1147. * @param string $type 变量类型
  1148. * @return mixed
  1149. */
  1150. public function except($name, $type = 'param')
  1151. {
  1152. $param = $this->$type();
  1153. if (is_string($name)) {
  1154. $name = explode(',', $name);
  1155. }
  1156. foreach ($name as $key) {
  1157. if (isset($param[$key])) {
  1158. unset($param[$key]);
  1159. }
  1160. }
  1161. return $param;
  1162. }
  1163. /**
  1164. * 当前是否ssl
  1165. * @access public
  1166. * @return bool
  1167. */
  1168. public function isSsl()
  1169. {
  1170. $server = array_merge($_SERVER, $this->server);
  1171. if (isset($server['HTTPS']) && ('1' == $server['HTTPS'] || 'on' == strtolower($server['HTTPS']))) {
  1172. return true;
  1173. } elseif (isset($server['REQUEST_SCHEME']) && 'https' == $server['REQUEST_SCHEME']) {
  1174. return true;
  1175. } elseif (isset($server['SERVER_PORT']) && ('443' == $server['SERVER_PORT'])) {
  1176. return true;
  1177. } elseif (isset($server['HTTP_X_FORWARDED_PROTO']) && 'https' == $server['HTTP_X_FORWARDED_PROTO']) {
  1178. return true;
  1179. } elseif (Config::get('https_agent_name') && isset($server[Config::get('https_agent_name')])) {
  1180. return true;
  1181. }
  1182. return false;
  1183. }
  1184. /**
  1185. * 当前是否Ajax请求
  1186. * @access public
  1187. * @param bool $ajax true 获取原始ajax请求
  1188. * @return bool
  1189. */
  1190. public function isAjax($ajax = false)
  1191. {
  1192. $value = $this->server('HTTP_X_REQUESTED_WITH', '', 'strtolower');
  1193. $result = ('xmlhttprequest' == $value) ? true : false;
  1194. if (true === $ajax) {
  1195. return $result;
  1196. } else {
  1197. $result = $this->param(Config::get('var_ajax')) ? true : $result;
  1198. $this->mergeParam = false;
  1199. return $result;
  1200. }
  1201. }
  1202. /**
  1203. * 当前是否Pjax请求
  1204. * @access public
  1205. * @param bool $pjax true 获取原始pjax请求
  1206. * @return bool
  1207. */
  1208. public function isPjax($pjax = false)
  1209. {
  1210. $result = !is_null($this->server('HTTP_X_PJAX')) ? true : false;
  1211. if (true === $pjax) {
  1212. return $result;
  1213. } else {
  1214. $result = $this->param(Config::get('var_pjax')) ? true : $result;
  1215. $this->mergeParam = false;
  1216. return $result;
  1217. }
  1218. }
  1219. /**
  1220. * 获取客户端IP地址
  1221. * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
  1222. * @param boolean $adv 是否进行高级模式获取(有可能被伪装)
  1223. * @return mixed
  1224. */
  1225. public function ip($type = 0, $adv = true)
  1226. {
  1227. $type = $type ? 1 : 0;
  1228. static $ip = null;
  1229. if (null !== $ip) {
  1230. return $ip[$type];
  1231. }
  1232. $httpAgentIp = Config::get('http_agent_ip');
  1233. if ($httpAgentIp && isset($_SERVER[$httpAgentIp])) {
  1234. $ip = $_SERVER[$httpAgentIp];
  1235. } elseif ($adv) {
  1236. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1237. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1238. $pos = array_search('unknown', $arr);
  1239. if (false !== $pos) {
  1240. unset($arr[$pos]);
  1241. }
  1242. $ip = trim(current($arr));
  1243. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1244. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1245. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1246. $ip = $_SERVER['REMOTE_ADDR'];
  1247. }
  1248. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1249. $ip = $_SERVER['REMOTE_ADDR'];
  1250. }
  1251. // IP地址合法验证
  1252. $long = sprintf("%u", ip2long($ip));
  1253. $ip = $long ? [$ip, $long] : ['0.0.0.0', 0];
  1254. return $ip[$type];
  1255. }
  1256. /**
  1257. * 检测是否使用手机访问
  1258. * @access public
  1259. * @return bool
  1260. */
  1261. public function isMobile()
  1262. {
  1263. if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) {
  1264. return true;
  1265. } elseif (isset($_SERVER['HTTP_ACCEPT']) && strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML")) {
  1266. return true;
  1267. } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {
  1268. return true;
  1269. } 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'])) {
  1270. return true;
  1271. } else {
  1272. return false;
  1273. }
  1274. }
  1275. /**
  1276. * 当前URL地址中的scheme参数
  1277. * @access public
  1278. * @return string
  1279. */
  1280. public function scheme()
  1281. {
  1282. return $this->isSsl() ? 'https' : 'http';
  1283. }
  1284. /**
  1285. * 当前请求URL地址中的query参数
  1286. * @access public
  1287. * @return string
  1288. */
  1289. public function query()
  1290. {
  1291. return $this->server('QUERY_STRING');
  1292. }
  1293. /**
  1294. * 当前请求的host
  1295. * @access public
  1296. * @param bool $strict true 仅仅获取HOST
  1297. * @return string
  1298. */
  1299. public function host($strict = false)
  1300. {
  1301. if (isset($_SERVER['HTTP_X_REAL_HOST'])) {
  1302. $host = $_SERVER['HTTP_X_REAL_HOST'];
  1303. } else {
  1304. $host = $this->server('HTTP_HOST');
  1305. }
  1306. return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
  1307. }
  1308. /**
  1309. * 当前请求URL地址中的port参数
  1310. * @access public
  1311. * @return integer
  1312. */
  1313. public function port()
  1314. {
  1315. return $this->server('SERVER_PORT');
  1316. }
  1317. /**
  1318. * 当前请求 SERVER_PROTOCOL
  1319. * @access public
  1320. * @return integer
  1321. */
  1322. public function protocol()
  1323. {
  1324. return $this->server('SERVER_PROTOCOL');
  1325. }
  1326. /**
  1327. * 当前请求 REMOTE_PORT
  1328. * @access public
  1329. * @return integer
  1330. */
  1331. public function remotePort()
  1332. {
  1333. return $this->server('REMOTE_PORT');
  1334. }
  1335. /**
  1336. * 当前请求 HTTP_CONTENT_TYPE
  1337. * @access public
  1338. * @return string
  1339. */
  1340. public function contentType()
  1341. {
  1342. $contentType = $this->server('CONTENT_TYPE');
  1343. if ($contentType) {
  1344. if (strpos($contentType, ';')) {
  1345. list($type) = explode(';', $contentType);
  1346. } else {
  1347. $type = $contentType;
  1348. }
  1349. return trim($type);
  1350. }
  1351. return '';
  1352. }
  1353. /**
  1354. * 获取当前请求的路由信息
  1355. * @access public
  1356. * @param array $route 路由名称
  1357. * @return array
  1358. */
  1359. public function routeInfo($route = [])
  1360. {
  1361. if (!empty($route)) {
  1362. $this->routeInfo = $route;
  1363. } else {
  1364. return $this->routeInfo;
  1365. }
  1366. }
  1367. /**
  1368. * 设置或者获取当前请求的调度信息
  1369. * @access public
  1370. * @param array $dispatch 调度信息
  1371. * @return array
  1372. */
  1373. public function dispatch($dispatch = null)
  1374. {
  1375. if (!is_null($dispatch)) {
  1376. $this->dispatch = $dispatch;
  1377. }
  1378. return $this->dispatch;
  1379. }
  1380. /**
  1381. * 设置或者获取当前的模块名
  1382. * @access public
  1383. * @param string $module 模块名
  1384. * @return string|Request
  1385. */
  1386. public function module($module = null)
  1387. {
  1388. if (!is_null($module)) {
  1389. $this->module = $module;
  1390. return $this;
  1391. } else {
  1392. return $this->module ?: '';
  1393. }
  1394. }
  1395. /**
  1396. * 设置或者获取当前的控制器名
  1397. * @access public
  1398. * @param string $controller 控制器名
  1399. * @return string|Request
  1400. */
  1401. public function controller($controller = null)
  1402. {
  1403. if (!is_null($controller)) {
  1404. $this->controller = $controller;
  1405. return $this;
  1406. } else {
  1407. return $this->controller ?: '';
  1408. }
  1409. }
  1410. /**
  1411. * 设置或者获取当前的操作名
  1412. * @access public
  1413. * @param string $action 操作名
  1414. * @return string|Request
  1415. */
  1416. public function action($action = null)
  1417. {
  1418. if (!is_null($action) && !is_bool($action)) {
  1419. $this->action = $action;
  1420. return $this;
  1421. } else {
  1422. $name = $this->action ?: '';
  1423. return true === $action ? $name : strtolower($name);
  1424. }
  1425. }
  1426. /**
  1427. * 设置或者获取当前的语言
  1428. * @access public
  1429. * @param string $lang 语言名
  1430. * @return string|Request
  1431. */
  1432. public function langset($lang = null)
  1433. {
  1434. if (!is_null($lang)) {
  1435. $this->langset = $lang;
  1436. return $this;
  1437. } else {
  1438. return $this->langset ?: '';
  1439. }
  1440. }
  1441. /**
  1442. * 设置或者获取当前请求的content
  1443. * @access public
  1444. * @return string
  1445. */
  1446. public function getContent()
  1447. {
  1448. if (is_null($this->content)) {
  1449. $this->content = $this->input;
  1450. }
  1451. return $this->content;
  1452. }
  1453. /**
  1454. * 获取当前请求的php://input
  1455. * @access public
  1456. * @return string
  1457. */
  1458. public function getInput()
  1459. {
  1460. return $this->input;
  1461. }
  1462. /**
  1463. * 生成请求令牌
  1464. * @access public
  1465. * @param string $name 令牌名称
  1466. * @param mixed $type 令牌生成方法
  1467. * @return string
  1468. */
  1469. public function token($name = '__token__', $type = 'md5')
  1470. {
  1471. $type = is_callable($type) ? $type : 'md5';
  1472. $token = call_user_func($type, $_SERVER['REQUEST_TIME_FLOAT']);
  1473. if ($this->isAjax()) {
  1474. header($name . ': ' . $token);
  1475. }
  1476. Session::set($name, $token);
  1477. return $token;
  1478. }
  1479. /**
  1480. * 设置当前地址的请求缓存
  1481. * @access public
  1482. * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id
  1483. * @param mixed $expire 缓存有效期
  1484. * @param array $except 缓存排除
  1485. * @param string $tag 缓存标签
  1486. * @return void
  1487. */
  1488. public function cache($key, $expire = null, $except = [], $tag = null)
  1489. {
  1490. if (!is_array($except)) {
  1491. $tag = $except;
  1492. $except = [];
  1493. }
  1494. if (false !== $key && $this->isGet() && !$this->isCheckCache) {
  1495. // 标记请求缓存检查
  1496. $this->isCheckCache = true;
  1497. if (false === $expire) {
  1498. // 关闭当前缓存
  1499. return;
  1500. }
  1501. if ($key instanceof \Closure) {
  1502. $key = call_user_func_array($key, [$this]);
  1503. } elseif (true === $key) {
  1504. foreach ($except as $rule) {
  1505. if (0 === stripos($this->url(), $rule)) {
  1506. return;
  1507. }
  1508. }
  1509. // 自动缓存功能
  1510. $key = '__URL__';
  1511. } elseif (strpos($key, '|')) {
  1512. list($key, $fun) = explode('|', $key);
  1513. }
  1514. // 特殊规则替换
  1515. if (false !== strpos($key, '__')) {
  1516. $key = str_replace(['__MODULE__', '__CONTROLLER__', '__ACTION__', '__URL__', ''], [$this->module, $this->controller, $this->action, md5($this->url(true))], $key);
  1517. }
  1518. if (false !== strpos($key, ':')) {
  1519. $param = $this->param();
  1520. foreach ($param as $item => $val) {
  1521. if (is_string($val) && false !== strpos($key, ':' . $item)) {
  1522. $key = str_replace(':' . $item, $val, $key);
  1523. }
  1524. }
  1525. } elseif (strpos($key, ']')) {
  1526. if ('[' . $this->ext() . ']' == $key) {
  1527. // 缓存某个后缀的请求
  1528. $key = md5($this->url());
  1529. } else {
  1530. return;
  1531. }
  1532. }
  1533. if (isset($fun)) {
  1534. $key = $fun($key);
  1535. }
  1536. if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) {
  1537. // 读取缓存
  1538. $response = Response::create()->code(304);
  1539. throw new \think\exception\HttpResponseException($response);
  1540. } elseif (Cache::has($key)) {
  1541. list($content, $header) = Cache::get($key);
  1542. $response = Response::create($content)->header($header);
  1543. throw new \think\exception\HttpResponseException($response);
  1544. } else {
  1545. $this->cache = [$key, $expire, $tag];
  1546. }
  1547. }
  1548. }
  1549. /**
  1550. * 读取请求缓存设置
  1551. * @access public
  1552. * @return array
  1553. */
  1554. public function getCache()
  1555. {
  1556. return $this->cache;
  1557. }
  1558. /**
  1559. * 设置当前请求绑定的对象实例
  1560. * @access public
  1561. * @param string|array $name 绑定的对象标识
  1562. * @param mixed $obj 绑定的对象实例
  1563. * @return mixed
  1564. */
  1565. public function bind($name, $obj = null)
  1566. {
  1567. if (is_array($name)) {
  1568. $this->bind = array_merge($this->bind, $name);
  1569. } else {
  1570. $this->bind[$name] = $obj;
  1571. }
  1572. }
  1573. public function __set($name, $value)
  1574. {
  1575. $this->bind[$name] = $value;
  1576. }
  1577. public function __get($name)
  1578. {
  1579. return isset($this->bind[$name]) ? $this->bind[$name] : null;
  1580. }
  1581. public function __isset($name)
  1582. {
  1583. return isset($this->bind[$name]);
  1584. }
  1585. }