Request.php 54 KB

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