Request.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2021 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. declare (strict_types = 1);
  12. namespace think;
  13. use ArrayAccess;
  14. use think\file\UploadedFile;
  15. use think\route\Rule;
  16. /**
  17. * 请求管理类
  18. * @package think
  19. */
  20. class Request implements ArrayAccess
  21. {
  22. /**
  23. * 兼容PATH_INFO获取
  24. * @var array
  25. */
  26. protected $pathinfoFetch = ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'];
  27. /**
  28. * PATHINFO变量名 用于兼容模式
  29. * @var string
  30. */
  31. protected $varPathinfo = 's';
  32. /**
  33. * 请求类型
  34. * @var string
  35. */
  36. protected $varMethod = '_method';
  37. /**
  38. * 表单ajax伪装变量
  39. * @var string
  40. */
  41. protected $varAjax = '_ajax';
  42. /**
  43. * 表单pjax伪装变量
  44. * @var string
  45. */
  46. protected $varPjax = '_pjax';
  47. /**
  48. * 域名根
  49. * @var string
  50. */
  51. protected $rootDomain = '';
  52. /**
  53. * HTTPS代理标识
  54. * @var string
  55. */
  56. protected $httpsAgentName = '';
  57. /**
  58. * 前端代理服务器IP
  59. * @var array
  60. */
  61. protected $proxyServerIp = [];
  62. /**
  63. * 前端代理服务器真实IP头
  64. * @var array
  65. */
  66. protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
  67. /**
  68. * 请求类型
  69. * @var string
  70. */
  71. protected $method;
  72. /**
  73. * 域名(含协议及端口)
  74. * @var string
  75. */
  76. protected $domain;
  77. /**
  78. * HOST(含端口)
  79. * @var string
  80. */
  81. protected $host;
  82. /**
  83. * 子域名
  84. * @var string
  85. */
  86. protected $subDomain;
  87. /**
  88. * 泛域名
  89. * @var string
  90. */
  91. protected $panDomain;
  92. /**
  93. * 当前URL地址
  94. * @var string
  95. */
  96. protected $url;
  97. /**
  98. * 基础URL
  99. * @var string
  100. */
  101. protected $baseUrl;
  102. /**
  103. * 当前执行的文件
  104. * @var string
  105. */
  106. protected $baseFile;
  107. /**
  108. * 访问的ROOT地址
  109. * @var string
  110. */
  111. protected $root;
  112. /**
  113. * pathinfo
  114. * @var string
  115. */
  116. protected $pathinfo;
  117. /**
  118. * pathinfo(不含后缀)
  119. * @var string
  120. */
  121. protected $path;
  122. /**
  123. * 当前请求的IP地址
  124. * @var string
  125. */
  126. protected $realIP;
  127. /**
  128. * 当前控制器名
  129. * @var string
  130. */
  131. protected $controller;
  132. /**
  133. * 当前操作名
  134. * @var string
  135. */
  136. protected $action;
  137. /**
  138. * 当前请求参数
  139. * @var array
  140. */
  141. protected $param = [];
  142. /**
  143. * 当前GET参数
  144. * @var array
  145. */
  146. protected $get = [];
  147. /**
  148. * 当前POST参数
  149. * @var array
  150. */
  151. protected $post = [];
  152. /**
  153. * 当前REQUEST参数
  154. * @var array
  155. */
  156. protected $request = [];
  157. /**
  158. * 当前路由对象
  159. * @var Rule
  160. */
  161. protected $rule;
  162. /**
  163. * 当前ROUTE参数
  164. * @var array
  165. */
  166. protected $route = [];
  167. /**
  168. * 中间件传递的参数
  169. * @var array
  170. */
  171. protected $middleware = [];
  172. /**
  173. * 当前PUT参数
  174. * @var array
  175. */
  176. protected $put;
  177. /**
  178. * SESSION对象
  179. * @var Session
  180. */
  181. protected $session;
  182. /**
  183. * COOKIE数据
  184. * @var array
  185. */
  186. protected $cookie = [];
  187. /**
  188. * ENV对象
  189. * @var Env
  190. */
  191. protected $env;
  192. /**
  193. * 当前SERVER参数
  194. * @var array
  195. */
  196. protected $server = [];
  197. /**
  198. * 当前FILE参数
  199. * @var array
  200. */
  201. protected $file = [];
  202. /**
  203. * 当前HEADER参数
  204. * @var array
  205. */
  206. protected $header = [];
  207. /**
  208. * 资源类型定义
  209. * @var array
  210. */
  211. protected $mimeType = [
  212. 'xml' => 'application/xml,text/xml,application/x-xml',
  213. 'json' => 'application/json,text/x-json,application/jsonrequest,text/json',
  214. 'js' => 'text/javascript,application/javascript,application/x-javascript',
  215. 'css' => 'text/css',
  216. 'rss' => 'application/rss+xml',
  217. 'yaml' => 'application/x-yaml,text/yaml',
  218. 'atom' => 'application/atom+xml',
  219. 'pdf' => 'application/pdf',
  220. 'text' => 'text/plain',
  221. 'image' => 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/webp,image/*',
  222. 'csv' => 'text/csv',
  223. 'html' => 'text/html,application/xhtml+xml,*/*',
  224. ];
  225. /**
  226. * 当前请求内容
  227. * @var string
  228. */
  229. protected $content;
  230. /**
  231. * 全局过滤规则
  232. * @var array
  233. */
  234. protected $filter;
  235. /**
  236. * php://input内容
  237. * @var string
  238. */
  239. // php://input
  240. protected $input;
  241. /**
  242. * 请求安全Key
  243. * @var string
  244. */
  245. protected $secureKey;
  246. /**
  247. * 是否合并Param
  248. * @var bool
  249. */
  250. protected $mergeParam = false;
  251. /**
  252. * 架构函数
  253. * @access public
  254. */
  255. public function __construct()
  256. {
  257. // 保存 php://input
  258. $this->input = file_get_contents('php://input');
  259. }
  260. public static function __make(App $app)
  261. {
  262. $request = new static();
  263. if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
  264. $header = $result;
  265. } else {
  266. $header = [];
  267. $server = $_SERVER;
  268. foreach ($server as $key => $val) {
  269. if (0 === strpos($key, 'HTTP_')) {
  270. $key = str_replace('_', '-', strtolower(substr($key, 5)));
  271. $header[$key] = $val;
  272. }
  273. }
  274. if (isset($server['CONTENT_TYPE'])) {
  275. $header['content-type'] = $server['CONTENT_TYPE'];
  276. }
  277. if (isset($server['CONTENT_LENGTH'])) {
  278. $header['content-length'] = $server['CONTENT_LENGTH'];
  279. }
  280. }
  281. $request->header = array_change_key_case($header);
  282. $request->server = $_SERVER;
  283. $request->env = $app->env;
  284. $inputData = $request->getInputData($request->input);
  285. $request->get = $_GET;
  286. $request->post = $_POST ?: $inputData;
  287. $request->put = $inputData;
  288. $request->request = $_REQUEST;
  289. $request->cookie = $_COOKIE;
  290. $request->file = $_FILES ?? [];
  291. return $request;
  292. }
  293. /**
  294. * 设置当前包含协议的域名
  295. * @access public
  296. * @param string $domain 域名
  297. * @return $this
  298. */
  299. public function setDomain(string $domain)
  300. {
  301. $this->domain = $domain;
  302. return $this;
  303. }
  304. /**
  305. * 获取当前包含协议的域名
  306. * @access public
  307. * @param bool $port 是否需要去除端口号
  308. * @return string
  309. */
  310. public function domain(bool $port = false): string
  311. {
  312. return $this->scheme() . '://' . $this->host($port);
  313. }
  314. /**
  315. * 获取当前根域名
  316. * @access public
  317. * @return string
  318. */
  319. public function rootDomain(): string
  320. {
  321. $root = $this->rootDomain;
  322. if (!$root) {
  323. $item = explode('.', $this->host());
  324. $count = count($item);
  325. $root = $count > 1 ? $item[$count - 2] . '.' . $item[$count - 1] : $item[0];
  326. }
  327. return $root;
  328. }
  329. /**
  330. * 设置当前泛域名的值
  331. * @access public
  332. * @param string $domain 域名
  333. * @return $this
  334. */
  335. public function setSubDomain(string $domain)
  336. {
  337. $this->subDomain = $domain;
  338. return $this;
  339. }
  340. /**
  341. * 获取当前子域名
  342. * @access public
  343. * @return string
  344. */
  345. public function subDomain(): string
  346. {
  347. if (is_null($this->subDomain)) {
  348. // 获取当前主域名
  349. $rootDomain = $this->rootDomain();
  350. if ($rootDomain) {
  351. $this->subDomain = rtrim(stristr($this->host(), $rootDomain, true), '.');
  352. } else {
  353. $this->subDomain = '';
  354. }
  355. }
  356. return $this->subDomain;
  357. }
  358. /**
  359. * 设置当前泛域名的值
  360. * @access public
  361. * @param string $domain 域名
  362. * @return $this
  363. */
  364. public function setPanDomain(string $domain)
  365. {
  366. $this->panDomain = $domain;
  367. return $this;
  368. }
  369. /**
  370. * 获取当前泛域名的值
  371. * @access public
  372. * @return string
  373. */
  374. public function panDomain(): string
  375. {
  376. return $this->panDomain ?: '';
  377. }
  378. /**
  379. * 设置当前完整URL 包括QUERY_STRING
  380. * @access public
  381. * @param string $url URL地址
  382. * @return $this
  383. */
  384. public function setUrl(string $url)
  385. {
  386. $this->url = $url;
  387. return $this;
  388. }
  389. /**
  390. * 获取当前完整URL 包括QUERY_STRING
  391. * @access public
  392. * @param bool $complete 是否包含完整域名
  393. * @return string
  394. */
  395. public function url(bool $complete = false): string
  396. {
  397. if ($this->url) {
  398. $url = $this->url;
  399. } elseif ($this->server('HTTP_X_REWRITE_URL')) {
  400. $url = $this->server('HTTP_X_REWRITE_URL');
  401. } elseif ($this->server('REQUEST_URI')) {
  402. $url = $this->server('REQUEST_URI');
  403. } elseif ($this->server('ORIG_PATH_INFO')) {
  404. $url = $this->server('ORIG_PATH_INFO') . (!empty($this->server('QUERY_STRING')) ? '?' . $this->server('QUERY_STRING') : '');
  405. } elseif (isset($_SERVER['argv'][1])) {
  406. $url = $_SERVER['argv'][1];
  407. } else {
  408. $url = '';
  409. }
  410. return $complete ? $this->domain() . $url : $url;
  411. }
  412. /**
  413. * 设置当前URL 不含QUERY_STRING
  414. * @access public
  415. * @param string $url URL地址
  416. * @return $this
  417. */
  418. public function setBaseUrl(string $url)
  419. {
  420. $this->baseUrl = $url;
  421. return $this;
  422. }
  423. /**
  424. * 获取当前URL 不含QUERY_STRING
  425. * @access public
  426. * @param bool $complete 是否包含完整域名
  427. * @return string
  428. */
  429. public function baseUrl(bool $complete = false): string
  430. {
  431. if (!$this->baseUrl) {
  432. $str = $this->url();
  433. $this->baseUrl = strpos($str, '?') ? strstr($str, '?', true) : $str;
  434. }
  435. return $complete ? $this->domain() . $this->baseUrl : $this->baseUrl;
  436. }
  437. /**
  438. * 获取当前执行的文件 SCRIPT_NAME
  439. * @access public
  440. * @param bool $complete 是否包含完整域名
  441. * @return string
  442. */
  443. public function baseFile(bool $complete = false): string
  444. {
  445. if (!$this->baseFile) {
  446. $url = '';
  447. if (!$this->isCli()) {
  448. $script_name = basename($this->server('SCRIPT_FILENAME'));
  449. if (basename($this->server('SCRIPT_NAME')) === $script_name) {
  450. $url = $this->server('SCRIPT_NAME');
  451. } elseif (basename($this->server('PHP_SELF')) === $script_name) {
  452. $url = $this->server('PHP_SELF');
  453. } elseif (basename($this->server('ORIG_SCRIPT_NAME')) === $script_name) {
  454. $url = $this->server('ORIG_SCRIPT_NAME');
  455. } elseif (($pos = strpos($this->server('PHP_SELF'), '/' . $script_name)) !== false) {
  456. $url = substr($this->server('SCRIPT_NAME'), 0, $pos) . '/' . $script_name;
  457. } elseif ($this->server('DOCUMENT_ROOT') && strpos($this->server('SCRIPT_FILENAME'), $this->server('DOCUMENT_ROOT')) === 0) {
  458. $url = str_replace('\\', '/', str_replace($this->server('DOCUMENT_ROOT'), '', $this->server('SCRIPT_FILENAME')));
  459. }
  460. }
  461. $this->baseFile = $url;
  462. }
  463. return $complete ? $this->domain() . $this->baseFile : $this->baseFile;
  464. }
  465. /**
  466. * 设置URL访问根地址
  467. * @access public
  468. * @param string $url URL地址
  469. * @return $this
  470. */
  471. public function setRoot(string $url)
  472. {
  473. $this->root = $url;
  474. return $this;
  475. }
  476. /**
  477. * 获取URL访问根地址
  478. * @access public
  479. * @param bool $complete 是否包含完整域名
  480. * @return string
  481. */
  482. public function root(bool $complete = false): string
  483. {
  484. if (!$this->root) {
  485. $file = $this->baseFile();
  486. if ($file && 0 !== strpos($this->url(), $file)) {
  487. $file = str_replace('\\', '/', dirname($file));
  488. }
  489. $this->root = rtrim($file, '/');
  490. }
  491. return $complete ? $this->domain() . $this->root : $this->root;
  492. }
  493. /**
  494. * 获取URL访问根目录
  495. * @access public
  496. * @return string
  497. */
  498. public function rootUrl(): string
  499. {
  500. $base = $this->root();
  501. $root = strpos($base, '.') ? ltrim(dirname($base), DIRECTORY_SEPARATOR) : $base;
  502. if ('' != $root) {
  503. $root = '/' . ltrim($root, '/');
  504. }
  505. return $root;
  506. }
  507. /**
  508. * 设置当前请求的pathinfo
  509. * @access public
  510. * @param string $pathinfo
  511. * @return $this
  512. */
  513. public function setPathinfo(string $pathinfo)
  514. {
  515. $this->pathinfo = $pathinfo;
  516. return $this;
  517. }
  518. /**
  519. * 获取当前请求URL的pathinfo信息(含URL后缀)
  520. * @access public
  521. * @return string
  522. */
  523. public function pathinfo(): string
  524. {
  525. if (is_null($this->pathinfo)) {
  526. if (isset($_GET[$this->varPathinfo])) {
  527. // 判断URL里面是否有兼容模式参数
  528. $pathinfo = $_GET[$this->varPathinfo];
  529. unset($_GET[$this->varPathinfo]);
  530. unset($this->get[$this->varPathinfo]);
  531. } elseif ($this->server('PATH_INFO')) {
  532. $pathinfo = $this->server('PATH_INFO');
  533. } elseif (false !== strpos(PHP_SAPI, 'cli')) {
  534. $pathinfo = strpos($this->server('REQUEST_URI'), '?') ? strstr($this->server('REQUEST_URI'), '?', true) : $this->server('REQUEST_URI');
  535. }
  536. // 分析PATHINFO信息
  537. if (!isset($pathinfo)) {
  538. foreach ($this->pathinfoFetch as $type) {
  539. if ($this->server($type)) {
  540. $pathinfo = (0 === strpos($this->server($type), $this->server('SCRIPT_NAME'))) ?
  541. substr($this->server($type), strlen($this->server('SCRIPT_NAME'))) : $this->server($type);
  542. break;
  543. }
  544. }
  545. }
  546. if (!empty($pathinfo)) {
  547. unset($this->get[$pathinfo], $this->request[$pathinfo]);
  548. }
  549. $this->pathinfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
  550. }
  551. return $this->pathinfo;
  552. }
  553. /**
  554. * 当前URL的访问后缀
  555. * @access public
  556. * @return string
  557. */
  558. public function ext(): string
  559. {
  560. return pathinfo($this->pathinfo(), PATHINFO_EXTENSION);
  561. }
  562. /**
  563. * 获取当前请求的时间
  564. * @access public
  565. * @param bool $float 是否使用浮点类型
  566. * @return integer|float
  567. */
  568. public function time(bool $float = false)
  569. {
  570. return $float ? $this->server('REQUEST_TIME_FLOAT') : $this->server('REQUEST_TIME');
  571. }
  572. /**
  573. * 当前请求的资源类型
  574. * @access public
  575. * @return string
  576. */
  577. public function type(): string
  578. {
  579. $accept = $this->server('HTTP_ACCEPT');
  580. if (empty($accept)) {
  581. return '';
  582. }
  583. foreach ($this->mimeType as $key => $val) {
  584. $array = explode(',', $val);
  585. foreach ($array as $k => $v) {
  586. if (stristr($accept, $v)) {
  587. return $key;
  588. }
  589. }
  590. }
  591. return '';
  592. }
  593. /**
  594. * 设置资源类型
  595. * @access public
  596. * @param string|array $type 资源类型名
  597. * @param string $val 资源类型
  598. * @return void
  599. */
  600. public function mimeType($type, $val = ''): void
  601. {
  602. if (is_array($type)) {
  603. $this->mimeType = array_merge($this->mimeType, $type);
  604. } else {
  605. $this->mimeType[$type] = $val;
  606. }
  607. }
  608. /**
  609. * 设置请求类型
  610. * @access public
  611. * @param string $method 请求类型
  612. * @return $this
  613. */
  614. public function setMethod(string $method)
  615. {
  616. $this->method = strtoupper($method);
  617. return $this;
  618. }
  619. /**
  620. * 当前的请求类型
  621. * @access public
  622. * @param bool $origin 是否获取原始请求类型
  623. * @return string
  624. */
  625. public function method(bool $origin = false): string
  626. {
  627. if ($origin) {
  628. // 获取原始请求类型
  629. return $this->server('REQUEST_METHOD') ?: 'GET';
  630. } elseif (!$this->method) {
  631. if (isset($this->post[$this->varMethod])) {
  632. $method = strtolower($this->post[$this->varMethod]);
  633. if (in_array($method, ['get', 'post', 'put', 'patch', 'delete'])) {
  634. $this->method = strtoupper($method);
  635. $this->{$method} = $this->post;
  636. } else {
  637. $this->method = 'POST';
  638. }
  639. unset($this->post[$this->varMethod]);
  640. } elseif ($this->server('HTTP_X_HTTP_METHOD_OVERRIDE')) {
  641. $this->method = strtoupper($this->server('HTTP_X_HTTP_METHOD_OVERRIDE'));
  642. } else {
  643. $this->method = $this->server('REQUEST_METHOD') ?: 'GET';
  644. }
  645. }
  646. return $this->method;
  647. }
  648. /**
  649. * 是否为GET请求
  650. * @access public
  651. * @return bool
  652. */
  653. public function isGet(): bool
  654. {
  655. return $this->method() == 'GET';
  656. }
  657. /**
  658. * 是否为POST请求
  659. * @access public
  660. * @return bool
  661. */
  662. public function isPost(): bool
  663. {
  664. return $this->method() == 'POST';
  665. }
  666. /**
  667. * 是否为PUT请求
  668. * @access public
  669. * @return bool
  670. */
  671. public function isPut(): bool
  672. {
  673. return $this->method() == 'PUT';
  674. }
  675. /**
  676. * 是否为DELTE请求
  677. * @access public
  678. * @return bool
  679. */
  680. public function isDelete(): bool
  681. {
  682. return $this->method() == 'DELETE';
  683. }
  684. /**
  685. * 是否为HEAD请求
  686. * @access public
  687. * @return bool
  688. */
  689. public function isHead(): bool
  690. {
  691. return $this->method() == 'HEAD';
  692. }
  693. /**
  694. * 是否为PATCH请求
  695. * @access public
  696. * @return bool
  697. */
  698. public function isPatch(): bool
  699. {
  700. return $this->method() == 'PATCH';
  701. }
  702. /**
  703. * 是否为OPTIONS请求
  704. * @access public
  705. * @return bool
  706. */
  707. public function isOptions(): bool
  708. {
  709. return $this->method() == 'OPTIONS';
  710. }
  711. /**
  712. * 是否为cli
  713. * @access public
  714. * @return bool
  715. */
  716. public function isCli(): bool
  717. {
  718. return PHP_SAPI == 'cli';
  719. }
  720. /**
  721. * 是否为cgi
  722. * @access public
  723. * @return bool
  724. */
  725. public function isCgi(): bool
  726. {
  727. return strpos(PHP_SAPI, 'cgi') === 0;
  728. }
  729. /**
  730. * 获取当前请求的参数
  731. * @access public
  732. * @param string|array $name 变量名
  733. * @param mixed $default 默认值
  734. * @param string|array $filter 过滤方法
  735. * @return mixed
  736. */
  737. public function param($name = '', $default = null, $filter = '')
  738. {
  739. if (empty($this->mergeParam)) {
  740. $method = $this->method(true);
  741. // 自动获取请求变量
  742. switch ($method) {
  743. case 'POST':
  744. $vars = $this->post(false);
  745. break;
  746. case 'PUT':
  747. case 'DELETE':
  748. case 'PATCH':
  749. $vars = $this->put(false);
  750. break;
  751. default:
  752. $vars = [];
  753. }
  754. // 当前请求参数和URL地址中的参数合并
  755. $this->param = array_merge($this->param, $this->get(false), $vars, $this->route(false));
  756. $this->mergeParam = true;
  757. }
  758. if (is_array($name)) {
  759. return $this->only($name, $this->param, $filter);
  760. }
  761. return $this->input($this->param, $name, $default, $filter);
  762. }
  763. /**
  764. * 设置路由变量
  765. * @access public
  766. * @param Rule $rule 路由对象
  767. * @return $this
  768. */
  769. public function setRule(Rule $rule)
  770. {
  771. $this->rule = $rule;
  772. return $this;
  773. }
  774. /**
  775. * 获取当前路由对象
  776. * @access public
  777. * @return Rule|null
  778. */
  779. public function rule()
  780. {
  781. return $this->rule;
  782. }
  783. /**
  784. * 设置路由变量
  785. * @access public
  786. * @param array $route 路由变量
  787. * @return $this
  788. */
  789. public function setRoute(array $route)
  790. {
  791. $this->route = array_merge($this->route, $route);
  792. $this->mergeParam = false;
  793. return $this;
  794. }
  795. /**
  796. * 获取路由参数
  797. * @access public
  798. * @param string|array $name 变量名
  799. * @param mixed $default 默认值
  800. * @param string|array $filter 过滤方法
  801. * @return mixed
  802. */
  803. public function route($name = '', $default = null, $filter = '')
  804. {
  805. if (is_array($name)) {
  806. return $this->only($name, $this->route, $filter);
  807. }
  808. return $this->input($this->route, $name, $default, $filter);
  809. }
  810. /**
  811. * 获取GET参数
  812. * @access public
  813. * @param string|array $name 变量名
  814. * @param mixed $default 默认值
  815. * @param string|array $filter 过滤方法
  816. * @return mixed
  817. */
  818. public function get($name = '', $default = null, $filter = '')
  819. {
  820. if (is_array($name)) {
  821. return $this->only($name, $this->get, $filter);
  822. }
  823. return $this->input($this->get, $name, $default, $filter);
  824. }
  825. /**
  826. * 获取中间件传递的参数
  827. * @access public
  828. * @param mixed $name 变量名
  829. * @param mixed $default 默认值
  830. * @return mixed
  831. */
  832. public function middleware($name, $default = null)
  833. {
  834. return $this->middleware[$name] ?? $default;
  835. }
  836. /**
  837. * 获取POST参数
  838. * @access public
  839. * @param string|array $name 变量名
  840. * @param mixed $default 默认值
  841. * @param string|array $filter 过滤方法
  842. * @return mixed
  843. */
  844. public function post($name = '', $default = null, $filter = '')
  845. {
  846. if (is_array($name)) {
  847. return $this->only($name, $this->post, $filter);
  848. }
  849. return $this->input($this->post, $name, $default, $filter);
  850. }
  851. /**
  852. * 获取PUT参数
  853. * @access public
  854. * @param string|array $name 变量名
  855. * @param mixed $default 默认值
  856. * @param string|array $filter 过滤方法
  857. * @return mixed
  858. */
  859. public function put($name = '', $default = null, $filter = '')
  860. {
  861. if (is_array($name)) {
  862. return $this->only($name, $this->put, $filter);
  863. }
  864. return $this->input($this->put, $name, $default, $filter);
  865. }
  866. protected function getInputData($content): array
  867. {
  868. $contentType = $this->contentType();
  869. if ('application/x-www-form-urlencoded' == $contentType) {
  870. parse_str($content, $data);
  871. return $data;
  872. } elseif (false !== strpos($contentType, 'json')) {
  873. return (array) json_decode($content, true);
  874. }
  875. return [];
  876. }
  877. /**
  878. * 设置获取DELETE参数
  879. * @access public
  880. * @param mixed $name 变量名
  881. * @param mixed $default 默认值
  882. * @param string|array $filter 过滤方法
  883. * @return mixed
  884. */
  885. public function delete($name = '', $default = null, $filter = '')
  886. {
  887. return $this->put($name, $default, $filter);
  888. }
  889. /**
  890. * 设置获取PATCH参数
  891. * @access public
  892. * @param mixed $name 变量名
  893. * @param mixed $default 默认值
  894. * @param string|array $filter 过滤方法
  895. * @return mixed
  896. */
  897. public function patch($name = '', $default = null, $filter = '')
  898. {
  899. return $this->put($name, $default, $filter);
  900. }
  901. /**
  902. * 获取request变量
  903. * @access public
  904. * @param string|array $name 数据名称
  905. * @param mixed $default 默认值
  906. * @param string|array $filter 过滤方法
  907. * @return mixed
  908. */
  909. public function request($name = '', $default = null, $filter = '')
  910. {
  911. if (is_array($name)) {
  912. return $this->only($name, $this->request, $filter);
  913. }
  914. return $this->input($this->request, $name, $default, $filter);
  915. }
  916. /**
  917. * 获取环境变量
  918. * @access public
  919. * @param string $name 数据名称
  920. * @param string $default 默认值
  921. * @return mixed
  922. */
  923. public function env(string $name = '', string $default = null)
  924. {
  925. if (empty($name)) {
  926. return $this->env->get();
  927. } else {
  928. $name = strtoupper($name);
  929. }
  930. return $this->env->get($name, $default);
  931. }
  932. /**
  933. * 获取session数据
  934. * @access public
  935. * @param string $name 数据名称
  936. * @param string $default 默认值
  937. * @return mixed
  938. */
  939. public function session(string $name = '', $default = null)
  940. {
  941. if ('' === $name) {
  942. return $this->session->all();
  943. }
  944. return $this->session->get($name, $default);
  945. }
  946. /**
  947. * 获取cookie参数
  948. * @access public
  949. * @param mixed $name 数据名称
  950. * @param string $default 默认值
  951. * @param string|array $filter 过滤方法
  952. * @return mixed
  953. */
  954. public function cookie(string $name = '', $default = null, $filter = '')
  955. {
  956. if (!empty($name)) {
  957. $data = $this->getData($this->cookie, $name, $default);
  958. } else {
  959. $data = $this->cookie;
  960. }
  961. // 解析过滤器
  962. $filter = $this->getFilter($filter, $default);
  963. if (is_array($data)) {
  964. array_walk_recursive($data, [$this, 'filterValue'], $filter);
  965. } else {
  966. $this->filterValue($data, $name, $filter);
  967. }
  968. return $data;
  969. }
  970. /**
  971. * 获取server参数
  972. * @access public
  973. * @param string $name 数据名称
  974. * @param string $default 默认值
  975. * @return mixed
  976. */
  977. public function server(string $name = '', string $default = '')
  978. {
  979. if (empty($name)) {
  980. return $this->server;
  981. } else {
  982. $name = strtoupper($name);
  983. }
  984. return $this->server[$name] ?? $default;
  985. }
  986. /**
  987. * 获取上传的文件信息
  988. * @access public
  989. * @param string $name 名称
  990. * @return null|array|UploadedFile
  991. */
  992. public function file(string $name = '')
  993. {
  994. $files = $this->file;
  995. if (!empty($files)) {
  996. if (strpos($name, '.')) {
  997. [$name, $sub] = explode('.', $name);
  998. }
  999. // 处理上传文件
  1000. $array = $this->dealUploadFile($files, $name);
  1001. if ('' === $name) {
  1002. // 获取全部文件
  1003. return $array;
  1004. } elseif (isset($sub) && isset($array[$name][$sub])) {
  1005. return $array[$name][$sub];
  1006. } elseif (isset($array[$name])) {
  1007. return $array[$name];
  1008. }
  1009. }
  1010. }
  1011. protected function dealUploadFile(array $files, string $name): array
  1012. {
  1013. $array = [];
  1014. foreach ($files as $key => $file) {
  1015. if (is_array($file['name'])) {
  1016. $item = [];
  1017. $keys = array_keys($file);
  1018. $count = count($file['name']);
  1019. for ($i = 0; $i < $count; $i++) {
  1020. if ($file['error'][$i] > 0) {
  1021. if ($name == $key) {
  1022. $this->throwUploadFileError($file['error'][$i]);
  1023. } else {
  1024. continue;
  1025. }
  1026. }
  1027. $temp['key'] = $key;
  1028. foreach ($keys as $_key) {
  1029. $temp[$_key] = $file[$_key][$i];
  1030. }
  1031. $item[] = new UploadedFile($temp['tmp_name'], $temp['name'], $temp['type'], $temp['error']);
  1032. }
  1033. $array[$key] = $item;
  1034. } else {
  1035. if ($file instanceof File) {
  1036. $array[$key] = $file;
  1037. } else {
  1038. if ($file['error'] > 0) {
  1039. if ($key == $name) {
  1040. $this->throwUploadFileError($file['error']);
  1041. } else {
  1042. continue;
  1043. }
  1044. }
  1045. $array[$key] = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['error']);
  1046. }
  1047. }
  1048. }
  1049. return $array;
  1050. }
  1051. protected function throwUploadFileError($error)
  1052. {
  1053. static $fileUploadErrors = [
  1054. 1 => 'upload File size exceeds the maximum value',
  1055. 2 => 'upload File size exceeds the maximum value',
  1056. 3 => 'only the portion of file is uploaded',
  1057. 4 => 'no file to uploaded',
  1058. 6 => 'upload temp dir not found',
  1059. 7 => 'file write error',
  1060. ];
  1061. $msg = $fileUploadErrors[$error];
  1062. throw new Exception($msg, $error);
  1063. }
  1064. /**
  1065. * 设置或者获取当前的Header
  1066. * @access public
  1067. * @param string $name header名称
  1068. * @param string $default 默认值
  1069. * @return string|array
  1070. */
  1071. public function header(string $name = '', string $default = null)
  1072. {
  1073. if ('' === $name) {
  1074. return $this->header;
  1075. }
  1076. $name = str_replace('_', '-', strtolower($name));
  1077. return $this->header[$name] ?? $default;
  1078. }
  1079. /**
  1080. * 获取变量 支持过滤和默认值
  1081. * @access public
  1082. * @param array $data 数据源
  1083. * @param string|false $name 字段名
  1084. * @param mixed $default 默认值
  1085. * @param string|array $filter 过滤函数
  1086. * @return mixed
  1087. */
  1088. public function input(array $data = [], $name = '', $default = null, $filter = '')
  1089. {
  1090. if (false === $name) {
  1091. // 获取原始数据
  1092. return $data;
  1093. }
  1094. $name = (string) $name;
  1095. if ('' != $name) {
  1096. // 解析name
  1097. if (strpos($name, '/')) {
  1098. [$name, $type] = explode('/', $name);
  1099. }
  1100. $data = $this->getData($data, $name);
  1101. if (is_null($data)) {
  1102. return $default;
  1103. }
  1104. if (is_object($data)) {
  1105. return $data;
  1106. }
  1107. }
  1108. $data = $this->filterData($data, $filter, $name, $default);
  1109. if (isset($type) && $data !== $default) {
  1110. // 强制类型转换
  1111. $this->typeCast($data, $type);
  1112. }
  1113. return $data;
  1114. }
  1115. protected function filterData($data, $filter, $name, $default)
  1116. {
  1117. // 解析过滤器
  1118. $filter = $this->getFilter($filter, $default);
  1119. if (is_array($data)) {
  1120. array_walk_recursive($data, [$this, 'filterValue'], $filter);
  1121. } else {
  1122. $this->filterValue($data, $name, $filter);
  1123. }
  1124. return $data;
  1125. }
  1126. /**
  1127. * 强制类型转换
  1128. * @access public
  1129. * @param mixed $data
  1130. * @param string $type
  1131. * @return mixed
  1132. */
  1133. private function typeCast(&$data, string $type)
  1134. {
  1135. switch (strtolower($type)) {
  1136. // 数组
  1137. case 'a':
  1138. $data = (array) $data;
  1139. break;
  1140. // 数字
  1141. case 'd':
  1142. $data = (int) $data;
  1143. break;
  1144. // 浮点
  1145. case 'f':
  1146. $data = (float) $data;
  1147. break;
  1148. // 布尔
  1149. case 'b':
  1150. $data = (boolean) $data;
  1151. break;
  1152. // 字符串
  1153. case 's':
  1154. if (is_scalar($data)) {
  1155. $data = (string) $data;
  1156. } else {
  1157. throw new \InvalidArgumentException('variable type error:' . gettype($data));
  1158. }
  1159. break;
  1160. }
  1161. }
  1162. /**
  1163. * 获取数据
  1164. * @access public
  1165. * @param array $data 数据源
  1166. * @param string $name 字段名
  1167. * @param mixed $default 默认值
  1168. * @return mixed
  1169. */
  1170. protected function getData(array $data, string $name, $default = null)
  1171. {
  1172. foreach (explode('.', $name) as $val) {
  1173. if (isset($data[$val])) {
  1174. $data = $data[$val];
  1175. } else {
  1176. return $default;
  1177. }
  1178. }
  1179. return $data;
  1180. }
  1181. /**
  1182. * 设置或获取当前的过滤规则
  1183. * @access public
  1184. * @param mixed $filter 过滤规则
  1185. * @return mixed
  1186. */
  1187. public function filter($filter = null)
  1188. {
  1189. if (is_null($filter)) {
  1190. return $this->filter;
  1191. }
  1192. $this->filter = $filter;
  1193. return $this;
  1194. }
  1195. protected function getFilter($filter, $default): array
  1196. {
  1197. if (is_null($filter)) {
  1198. $filter = [];
  1199. } else {
  1200. $filter = $filter ?: $this->filter;
  1201. if (is_string($filter) && false === strpos($filter, '/')) {
  1202. $filter = explode(',', $filter);
  1203. } else {
  1204. $filter = (array) $filter;
  1205. }
  1206. }
  1207. $filter[] = $default;
  1208. return $filter;
  1209. }
  1210. /**
  1211. * 递归过滤给定的值
  1212. * @access public
  1213. * @param mixed $value 键值
  1214. * @param mixed $key 键名
  1215. * @param array $filters 过滤方法+默认值
  1216. * @return mixed
  1217. */
  1218. public function filterValue(&$value, $key, $filters)
  1219. {
  1220. $default = array_pop($filters);
  1221. foreach ($filters as $filter) {
  1222. if (is_callable($filter)) {
  1223. // 调用函数或者方法过滤
  1224. $value = call_user_func($filter, $value);
  1225. } elseif (is_scalar($value)) {
  1226. if (is_string($filter) && false !== strpos($filter, '/')) {
  1227. // 正则过滤
  1228. if (!preg_match($filter, $value)) {
  1229. // 匹配不成功返回默认值
  1230. $value = $default;
  1231. break;
  1232. }
  1233. } elseif (!empty($filter)) {
  1234. // filter函数不存在时, 则使用filter_var进行过滤
  1235. // filter为非整形值时, 调用filter_id取得过滤id
  1236. $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
  1237. if (false === $value) {
  1238. $value = $default;
  1239. break;
  1240. }
  1241. }
  1242. }
  1243. }
  1244. return $value;
  1245. }
  1246. /**
  1247. * 是否存在某个请求参数
  1248. * @access public
  1249. * @param string $name 变量名
  1250. * @param string $type 变量类型
  1251. * @param bool $checkEmpty 是否检测空值
  1252. * @return bool
  1253. */
  1254. public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
  1255. {
  1256. if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
  1257. return false;
  1258. }
  1259. $param = empty($this->$type) ? $this->$type() : $this->$type;
  1260. if (is_object($param)) {
  1261. return $param->has($name);
  1262. }
  1263. // 按.拆分成多维数组进行判断
  1264. foreach (explode('.', $name) as $val) {
  1265. if (isset($param[$val])) {
  1266. $param = $param[$val];
  1267. } else {
  1268. return false;
  1269. }
  1270. }
  1271. return ($checkEmpty && '' === $param) ? false : true;
  1272. }
  1273. /**
  1274. * 获取指定的参数
  1275. * @access public
  1276. * @param array $name 变量名
  1277. * @param mixed $data 数据或者变量类型
  1278. * @param string|array $filter 过滤方法
  1279. * @return array
  1280. */
  1281. public function only(array $name, $data = 'param', $filter = ''): array
  1282. {
  1283. $data = is_array($data) ? $data : $this->$data();
  1284. $item = [];
  1285. foreach ($name as $key => $val) {
  1286. if (is_int($key)) {
  1287. $default = null;
  1288. $key = $val;
  1289. if (!isset($data[$key])) {
  1290. continue;
  1291. }
  1292. } else {
  1293. $default = $val;
  1294. }
  1295. $item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
  1296. }
  1297. return $item;
  1298. }
  1299. /**
  1300. * 排除指定参数获取
  1301. * @access public
  1302. * @param array $name 变量名
  1303. * @param string $type 变量类型
  1304. * @return mixed
  1305. */
  1306. public function except(array $name, string $type = 'param'): array
  1307. {
  1308. $param = $this->$type();
  1309. foreach ($name as $key) {
  1310. if (isset($param[$key])) {
  1311. unset($param[$key]);
  1312. }
  1313. }
  1314. return $param;
  1315. }
  1316. /**
  1317. * 当前是否ssl
  1318. * @access public
  1319. * @return bool
  1320. */
  1321. public function isSsl(): bool
  1322. {
  1323. if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
  1324. return true;
  1325. } elseif ('https' == $this->server('REQUEST_SCHEME')) {
  1326. return true;
  1327. } elseif ('443' == $this->server('SERVER_PORT')) {
  1328. return true;
  1329. } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
  1330. return true;
  1331. } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
  1332. return true;
  1333. }
  1334. return false;
  1335. }
  1336. /**
  1337. * 当前是否JSON请求
  1338. * @access public
  1339. * @return bool
  1340. */
  1341. public function isJson(): bool
  1342. {
  1343. $acceptType = $this->type();
  1344. return false !== strpos($acceptType, 'json');
  1345. }
  1346. /**
  1347. * 当前是否Ajax请求
  1348. * @access public
  1349. * @param bool $ajax true 获取原始ajax请求
  1350. * @return bool
  1351. */
  1352. public function isAjax(bool $ajax = false): bool
  1353. {
  1354. $value = $this->server('HTTP_X_REQUESTED_WITH');
  1355. $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
  1356. if (true === $ajax) {
  1357. return $result;
  1358. }
  1359. return $this->param($this->varAjax) ? true : $result;
  1360. }
  1361. /**
  1362. * 当前是否Pjax请求
  1363. * @access public
  1364. * @param bool $pjax true 获取原始pjax请求
  1365. * @return bool
  1366. */
  1367. public function isPjax(bool $pjax = false): bool
  1368. {
  1369. $result = !empty($this->server('HTTP_X_PJAX')) ? true : false;
  1370. if (true === $pjax) {
  1371. return $result;
  1372. }
  1373. return $this->param($this->varPjax) ? true : $result;
  1374. }
  1375. /**
  1376. * 获取客户端IP地址
  1377. * @access public
  1378. * @return string
  1379. */
  1380. public function ip(): string
  1381. {
  1382. if (!empty($this->realIP)) {
  1383. return $this->realIP;
  1384. }
  1385. $this->realIP = $this->server('REMOTE_ADDR', '');
  1386. // 如果指定了前端代理服务器IP以及其会发送的IP头
  1387. // 则尝试获取前端代理服务器发送过来的真实IP
  1388. $proxyIp = $this->proxyServerIp;
  1389. $proxyIpHeader = $this->proxyServerIpHeader;
  1390. if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
  1391. // 从指定的HTTP头中依次尝试获取IP地址
  1392. // 直到获取到一个合法的IP地址
  1393. foreach ($proxyIpHeader as $header) {
  1394. $tempIP = $this->server($header);
  1395. if (empty($tempIP)) {
  1396. continue;
  1397. }
  1398. $tempIP = trim(explode(',', $tempIP)[0]);
  1399. if (!$this->isValidIP($tempIP)) {
  1400. $tempIP = null;
  1401. } else {
  1402. break;
  1403. }
  1404. }
  1405. // tempIP不为空,说明获取到了一个IP地址
  1406. // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
  1407. // 如果是的话说明该 IP头 是由前端代理服务器设置的
  1408. // 否则则是伪装的
  1409. if (!empty($tempIP)) {
  1410. $realIPBin = $this->ip2bin($this->realIP);
  1411. foreach ($proxyIp as $ip) {
  1412. $serverIPElements = explode('/', $ip);
  1413. $serverIP = $serverIPElements[0];
  1414. $serverIPPrefix = $serverIPElements[1] ?? 128;
  1415. $serverIPBin = $this->ip2bin($serverIP);
  1416. // IP类型不符
  1417. if (strlen($realIPBin) !== strlen($serverIPBin)) {
  1418. continue;
  1419. }
  1420. if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
  1421. $this->realIP = $tempIP;
  1422. break;
  1423. }
  1424. }
  1425. }
  1426. }
  1427. if (!$this->isValidIP($this->realIP)) {
  1428. $this->realIP = '0.0.0.0';
  1429. }
  1430. return $this->realIP;
  1431. }
  1432. /**
  1433. * 检测是否是合法的IP地址
  1434. *
  1435. * @param string $ip IP地址
  1436. * @param string $type IP地址类型 (ipv4, ipv6)
  1437. *
  1438. * @return boolean
  1439. */
  1440. public function isValidIP(string $ip, string $type = ''): bool
  1441. {
  1442. switch (strtolower($type)) {
  1443. case 'ipv4':
  1444. $flag = FILTER_FLAG_IPV4;
  1445. break;
  1446. case 'ipv6':
  1447. $flag = FILTER_FLAG_IPV6;
  1448. break;
  1449. default:
  1450. $flag = 0;
  1451. break;
  1452. }
  1453. return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
  1454. }
  1455. /**
  1456. * 将IP地址转换为二进制字符串
  1457. *
  1458. * @param string $ip
  1459. *
  1460. * @return string
  1461. */
  1462. public function ip2bin(string $ip): string
  1463. {
  1464. if ($this->isValidIP($ip, 'ipv6')) {
  1465. $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
  1466. foreach ($IPHex as $key => $value) {
  1467. $IPHex[$key] = intval($value, 16);
  1468. }
  1469. $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
  1470. } else {
  1471. $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
  1472. foreach ($IPHex as $key => $value) {
  1473. $IPHex[$key] = intval($value, 16);
  1474. }
  1475. $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
  1476. }
  1477. return $IPBin;
  1478. }
  1479. /**
  1480. * 检测是否使用手机访问
  1481. * @access public
  1482. * @return bool
  1483. */
  1484. public function isMobile(): bool
  1485. {
  1486. if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
  1487. return true;
  1488. } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
  1489. return true;
  1490. } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
  1491. return true;
  1492. } elseif ($this->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', $this->server('HTTP_USER_AGENT'))) {
  1493. return true;
  1494. }
  1495. return false;
  1496. }
  1497. /**
  1498. * 当前URL地址中的scheme参数
  1499. * @access public
  1500. * @return string
  1501. */
  1502. public function scheme(): string
  1503. {
  1504. return $this->isSsl() ? 'https' : 'http';
  1505. }
  1506. /**
  1507. * 当前请求URL地址中的query参数
  1508. * @access public
  1509. * @return string
  1510. */
  1511. public function query(): string
  1512. {
  1513. return $this->server('QUERY_STRING', '');
  1514. }
  1515. /**
  1516. * 设置当前请求的host(包含端口)
  1517. * @access public
  1518. * @param string $host 主机名(含端口)
  1519. * @return $this
  1520. */
  1521. public function setHost(string $host)
  1522. {
  1523. $this->host = $host;
  1524. return $this;
  1525. }
  1526. /**
  1527. * 当前请求的host
  1528. * @access public
  1529. * @param bool $strict true 仅仅获取HOST
  1530. * @return string
  1531. */
  1532. public function host(bool $strict = false): string
  1533. {
  1534. if ($this->host) {
  1535. $host = $this->host;
  1536. } else {
  1537. $host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
  1538. }
  1539. return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
  1540. }
  1541. /**
  1542. * 当前请求URL地址中的port参数
  1543. * @access public
  1544. * @return int
  1545. */
  1546. public function port(): int
  1547. {
  1548. return (int) ($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
  1549. }
  1550. /**
  1551. * 当前请求 SERVER_PROTOCOL
  1552. * @access public
  1553. * @return string
  1554. */
  1555. public function protocol(): string
  1556. {
  1557. return $this->server('SERVER_PROTOCOL', '');
  1558. }
  1559. /**
  1560. * 当前请求 REMOTE_PORT
  1561. * @access public
  1562. * @return int
  1563. */
  1564. public function remotePort(): int
  1565. {
  1566. return (int) $this->server('REMOTE_PORT', '');
  1567. }
  1568. /**
  1569. * 当前请求 HTTP_CONTENT_TYPE
  1570. * @access public
  1571. * @return string
  1572. */
  1573. public function contentType(): string
  1574. {
  1575. $contentType = $this->header('Content-Type');
  1576. if ($contentType) {
  1577. if (strpos($contentType, ';')) {
  1578. [$type] = explode(';', $contentType);
  1579. } else {
  1580. $type = $contentType;
  1581. }
  1582. return trim($type);
  1583. }
  1584. return '';
  1585. }
  1586. /**
  1587. * 获取当前请求的安全Key
  1588. * @access public
  1589. * @return string
  1590. */
  1591. public function secureKey(): string
  1592. {
  1593. if (is_null($this->secureKey)) {
  1594. $this->secureKey = uniqid('', true);
  1595. }
  1596. return $this->secureKey;
  1597. }
  1598. /**
  1599. * 设置当前的控制器名
  1600. * @access public
  1601. * @param string $controller 控制器名
  1602. * @return $this
  1603. */
  1604. public function setController(string $controller)
  1605. {
  1606. $this->controller = $controller;
  1607. return $this;
  1608. }
  1609. /**
  1610. * 设置当前的操作名
  1611. * @access public
  1612. * @param string $action 操作名
  1613. * @return $this
  1614. */
  1615. public function setAction(string $action)
  1616. {
  1617. $this->action = $action;
  1618. return $this;
  1619. }
  1620. /**
  1621. * 获取当前的控制器名
  1622. * @access public
  1623. * @param bool $convert 转换为小写
  1624. * @return string
  1625. */
  1626. public function controller(bool $convert = false): string
  1627. {
  1628. $name = $this->controller ?: '';
  1629. return $convert ? strtolower($name) : $name;
  1630. }
  1631. /**
  1632. * 获取当前的操作名
  1633. * @access public
  1634. * @param bool $convert 转换为小写
  1635. * @return string
  1636. */
  1637. public function action(bool $convert = false): string
  1638. {
  1639. $name = $this->action ?: '';
  1640. return $convert ? strtolower($name) : $name;
  1641. }
  1642. /**
  1643. * 设置或者获取当前请求的content
  1644. * @access public
  1645. * @return string
  1646. */
  1647. public function getContent(): string
  1648. {
  1649. if (is_null($this->content)) {
  1650. $this->content = $this->input;
  1651. }
  1652. return $this->content;
  1653. }
  1654. /**
  1655. * 获取当前请求的php://input
  1656. * @access public
  1657. * @return string
  1658. */
  1659. public function getInput(): string
  1660. {
  1661. return $this->input;
  1662. }
  1663. /**
  1664. * 生成请求令牌
  1665. * @access public
  1666. * @param string $name 令牌名称
  1667. * @param mixed $type 令牌生成方法
  1668. * @return string
  1669. */
  1670. public function buildToken(string $name = '__token__', $type = 'md5'): string
  1671. {
  1672. $type = is_callable($type) ? $type : 'md5';
  1673. $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
  1674. $this->session->set($name, $token);
  1675. return $token;
  1676. }
  1677. /**
  1678. * 检查请求令牌
  1679. * @access public
  1680. * @param string $token 令牌名称
  1681. * @param array $data 表单数据
  1682. * @return bool
  1683. */
  1684. public function checkToken(string $token = '__token__', array $data = []): bool
  1685. {
  1686. if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
  1687. return true;
  1688. }
  1689. if (!$this->session->has($token)) {
  1690. // 令牌数据无效
  1691. return false;
  1692. }
  1693. // Header验证
  1694. if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
  1695. // 防止重复提交
  1696. $this->session->delete($token); // 验证完成销毁session
  1697. return true;
  1698. }
  1699. if (empty($data)) {
  1700. $data = $this->post();
  1701. }
  1702. // 令牌验证
  1703. if (isset($data[$token]) && $this->session->get($token) === $data[$token]) {
  1704. // 防止重复提交
  1705. $this->session->delete($token); // 验证完成销毁session
  1706. return true;
  1707. }
  1708. // 开启TOKEN重置
  1709. $this->session->delete($token);
  1710. return false;
  1711. }
  1712. /**
  1713. * 设置在中间件传递的数据
  1714. * @access public
  1715. * @param array $middleware 数据
  1716. * @return $this
  1717. */
  1718. public function withMiddleware(array $middleware)
  1719. {
  1720. $this->middleware = array_merge($this->middleware, $middleware);
  1721. return $this;
  1722. }
  1723. /**
  1724. * 设置GET数据
  1725. * @access public
  1726. * @param array $get 数据
  1727. * @return $this
  1728. */
  1729. public function withGet(array $get)
  1730. {
  1731. $this->get = $get;
  1732. return $this;
  1733. }
  1734. /**
  1735. * 设置POST数据
  1736. * @access public
  1737. * @param array $post 数据
  1738. * @return $this
  1739. */
  1740. public function withPost(array $post)
  1741. {
  1742. $this->post = $post;
  1743. return $this;
  1744. }
  1745. /**
  1746. * 设置COOKIE数据
  1747. * @access public
  1748. * @param array $cookie 数据
  1749. * @return $this
  1750. */
  1751. public function withCookie(array $cookie)
  1752. {
  1753. $this->cookie = $cookie;
  1754. return $this;
  1755. }
  1756. /**
  1757. * 设置SESSION数据
  1758. * @access public
  1759. * @param Session $session 数据
  1760. * @return $this
  1761. */
  1762. public function withSession(Session $session)
  1763. {
  1764. $this->session = $session;
  1765. return $this;
  1766. }
  1767. /**
  1768. * 设置SERVER数据
  1769. * @access public
  1770. * @param array $server 数据
  1771. * @return $this
  1772. */
  1773. public function withServer(array $server)
  1774. {
  1775. $this->server = array_change_key_case($server, CASE_UPPER);
  1776. return $this;
  1777. }
  1778. /**
  1779. * 设置HEADER数据
  1780. * @access public
  1781. * @param array $header 数据
  1782. * @return $this
  1783. */
  1784. public function withHeader(array $header)
  1785. {
  1786. $this->header = array_change_key_case($header);
  1787. return $this;
  1788. }
  1789. /**
  1790. * 设置ENV数据
  1791. * @access public
  1792. * @param Env $env 数据
  1793. * @return $this
  1794. */
  1795. public function withEnv(Env $env)
  1796. {
  1797. $this->env = $env;
  1798. return $this;
  1799. }
  1800. /**
  1801. * 设置php://input数据
  1802. * @access public
  1803. * @param string $input RAW数据
  1804. * @return $this
  1805. */
  1806. public function withInput(string $input)
  1807. {
  1808. $this->input = $input;
  1809. if (!empty($input)) {
  1810. $inputData = $this->getInputData($input);
  1811. if (!empty($inputData)) {
  1812. $this->post = $inputData;
  1813. $this->put = $inputData;
  1814. }
  1815. }
  1816. return $this;
  1817. }
  1818. /**
  1819. * 设置文件上传数据
  1820. * @access public
  1821. * @param array $files 上传信息
  1822. * @return $this
  1823. */
  1824. public function withFiles(array $files)
  1825. {
  1826. $this->file = $files;
  1827. return $this;
  1828. }
  1829. /**
  1830. * 设置ROUTE变量
  1831. * @access public
  1832. * @param array $route 数据
  1833. * @return $this
  1834. */
  1835. public function withRoute(array $route)
  1836. {
  1837. $this->route = $route;
  1838. return $this;
  1839. }
  1840. /**
  1841. * 设置中间传递数据
  1842. * @access public
  1843. * @param string $name 参数名
  1844. * @param mixed $value 值
  1845. */
  1846. public function __set(string $name, $value)
  1847. {
  1848. $this->middleware[$name] = $value;
  1849. }
  1850. /**
  1851. * 获取中间传递数据的值
  1852. * @access public
  1853. * @param string $name 名称
  1854. * @return mixed
  1855. */
  1856. public function __get(string $name)
  1857. {
  1858. return $this->middleware($name);
  1859. }
  1860. /**
  1861. * 检测中间传递数据的值
  1862. * @access public
  1863. * @param string $name 名称
  1864. * @return boolean
  1865. */
  1866. public function __isset(string $name): bool
  1867. {
  1868. return isset($this->middleware[$name]);
  1869. }
  1870. // ArrayAccess
  1871. public function offsetExists($name): bool
  1872. {
  1873. return $this->has($name);
  1874. }
  1875. public function offsetGet($name)
  1876. {
  1877. return $this->param($name);
  1878. }
  1879. public function offsetSet($name, $value)
  1880. {}
  1881. public function offsetUnset($name)
  1882. {}
  1883. }