Request.php 54 KB

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