Request.php 53 KB

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