Request.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178
  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|null
  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. if (is_null($value)) {
  1244. continue;
  1245. }
  1246. $value = call_user_func($filter, $value);
  1247. } elseif (is_scalar($value)) {
  1248. if (is_string($filter) && false !== strpos($filter, '/')) {
  1249. // 正则过滤
  1250. if (!preg_match($filter, $value)) {
  1251. // 匹配不成功返回默认值
  1252. $value = $default;
  1253. break;
  1254. }
  1255. } elseif (!empty($filter)) {
  1256. // filter函数不存在时, 则使用filter_var进行过滤
  1257. // filter为非整形值时, 调用filter_id取得过滤id
  1258. $value = filter_var($value, is_int($filter) ? $filter : filter_id($filter));
  1259. if (false === $value) {
  1260. $value = $default;
  1261. break;
  1262. }
  1263. }
  1264. }
  1265. }
  1266. return $value;
  1267. }
  1268. /**
  1269. * 是否存在某个请求参数
  1270. * @access public
  1271. * @param string $name 变量名
  1272. * @param string $type 变量类型
  1273. * @param bool $checkEmpty 是否检测空值
  1274. * @return bool
  1275. */
  1276. public function has(string $name, string $type = 'param', bool $checkEmpty = false): bool
  1277. {
  1278. if (!in_array($type, ['param', 'get', 'post', 'put', 'patch', 'route', 'delete', 'cookie', 'session', 'env', 'request', 'server', 'header', 'file'])) {
  1279. return false;
  1280. }
  1281. $param = empty($this->$type) ? $this->$type() : $this->$type;
  1282. if (is_object($param)) {
  1283. return $param->has($name);
  1284. }
  1285. // 按.拆分成多维数组进行判断
  1286. foreach (explode('.', $name) as $val) {
  1287. if (isset($param[$val])) {
  1288. $param = $param[$val];
  1289. } else {
  1290. return false;
  1291. }
  1292. }
  1293. return ($checkEmpty && '' === $param) ? false : true;
  1294. }
  1295. /**
  1296. * 获取指定的参数
  1297. * @access public
  1298. * @param array $name 变量名
  1299. * @param mixed $data 数据或者变量类型
  1300. * @param string|array $filter 过滤方法
  1301. * @return array
  1302. */
  1303. public function only(array $name, $data = 'param', $filter = ''): array
  1304. {
  1305. $data = is_array($data) ? $data : $this->$data();
  1306. $item = [];
  1307. foreach ($name as $key => $val) {
  1308. if (is_int($key)) {
  1309. $default = null;
  1310. $key = $val;
  1311. if (!key_exists($key, $data)) {
  1312. continue;
  1313. }
  1314. } else {
  1315. $default = $val;
  1316. }
  1317. $item[$key] = $this->filterData($data[$key] ?? $default, $filter, $key, $default);
  1318. }
  1319. return $item;
  1320. }
  1321. /**
  1322. * 排除指定参数获取
  1323. * @access public
  1324. * @param array $name 变量名
  1325. * @param string $type 变量类型
  1326. * @return mixed
  1327. */
  1328. public function except(array $name, string $type = 'param'): array
  1329. {
  1330. $param = $this->$type();
  1331. foreach ($name as $key) {
  1332. if (isset($param[$key])) {
  1333. unset($param[$key]);
  1334. }
  1335. }
  1336. return $param;
  1337. }
  1338. /**
  1339. * 当前是否ssl
  1340. * @access public
  1341. * @return bool
  1342. */
  1343. public function isSsl(): bool
  1344. {
  1345. if ($this->server('HTTPS') && ('1' == $this->server('HTTPS') || 'on' == strtolower($this->server('HTTPS')))) {
  1346. return true;
  1347. } elseif ('https' == $this->server('REQUEST_SCHEME')) {
  1348. return true;
  1349. } elseif ('443' == $this->server('SERVER_PORT')) {
  1350. return true;
  1351. } elseif ('https' == $this->server('HTTP_X_FORWARDED_PROTO')) {
  1352. return true;
  1353. } elseif ($this->httpsAgentName && $this->server($this->httpsAgentName)) {
  1354. return true;
  1355. }
  1356. return false;
  1357. }
  1358. /**
  1359. * 当前是否JSON请求
  1360. * @access public
  1361. * @return bool
  1362. */
  1363. public function isJson(): bool
  1364. {
  1365. $acceptType = $this->type();
  1366. return false !== strpos($acceptType, 'json');
  1367. }
  1368. /**
  1369. * 当前是否Ajax请求
  1370. * @access public
  1371. * @param bool $ajax true 获取原始ajax请求
  1372. * @return bool
  1373. */
  1374. public function isAjax(bool $ajax = false): bool
  1375. {
  1376. $value = $this->server('HTTP_X_REQUESTED_WITH');
  1377. $result = $value && 'xmlhttprequest' == strtolower($value) ? true : false;
  1378. if (true === $ajax) {
  1379. return $result;
  1380. }
  1381. return $this->param($this->varAjax) ? true : $result;
  1382. }
  1383. /**
  1384. * 当前是否Pjax请求
  1385. * @access public
  1386. * @param bool $pjax true 获取原始pjax请求
  1387. * @return bool
  1388. */
  1389. public function isPjax(bool $pjax = false): bool
  1390. {
  1391. $result = !empty($this->server('HTTP_X_PJAX')) ? true : false;
  1392. if (true === $pjax) {
  1393. return $result;
  1394. }
  1395. return $this->param($this->varPjax) ? true : $result;
  1396. }
  1397. /**
  1398. * 获取客户端IP地址
  1399. * @access public
  1400. * @return string
  1401. */
  1402. public function ip(): string
  1403. {
  1404. if (!empty($this->realIP)) {
  1405. return $this->realIP;
  1406. }
  1407. $this->realIP = $this->server('REMOTE_ADDR', '');
  1408. // 如果指定了前端代理服务器IP以及其会发送的IP头
  1409. // 则尝试获取前端代理服务器发送过来的真实IP
  1410. $proxyIp = $this->proxyServerIp;
  1411. $proxyIpHeader = $this->proxyServerIpHeader;
  1412. if (count($proxyIp) > 0 && count($proxyIpHeader) > 0) {
  1413. // 从指定的HTTP头中依次尝试获取IP地址
  1414. // 直到获取到一个合法的IP地址
  1415. foreach ($proxyIpHeader as $header) {
  1416. $tempIP = $this->server($header);
  1417. if (empty($tempIP)) {
  1418. continue;
  1419. }
  1420. $tempIP = trim(explode(',', $tempIP)[0]);
  1421. if (!$this->isValidIP($tempIP)) {
  1422. $tempIP = null;
  1423. } else {
  1424. break;
  1425. }
  1426. }
  1427. // tempIP不为空,说明获取到了一个IP地址
  1428. // 这时我们检查 REMOTE_ADDR 是不是指定的前端代理服务器之一
  1429. // 如果是的话说明该 IP头 是由前端代理服务器设置的
  1430. // 否则则是伪装的
  1431. if (!empty($tempIP)) {
  1432. $realIPBin = $this->ip2bin($this->realIP);
  1433. foreach ($proxyIp as $ip) {
  1434. $serverIPElements = explode('/', $ip);
  1435. $serverIP = $serverIPElements[0];
  1436. $serverIPPrefix = $serverIPElements[1] ?? 128;
  1437. $serverIPBin = $this->ip2bin($serverIP);
  1438. // IP类型不符
  1439. if (strlen($realIPBin) !== strlen($serverIPBin)) {
  1440. continue;
  1441. }
  1442. if (strncmp($realIPBin, $serverIPBin, (int) $serverIPPrefix) === 0) {
  1443. $this->realIP = $tempIP;
  1444. break;
  1445. }
  1446. }
  1447. }
  1448. }
  1449. if (!$this->isValidIP($this->realIP)) {
  1450. $this->realIP = '0.0.0.0';
  1451. }
  1452. return $this->realIP;
  1453. }
  1454. /**
  1455. * 检测是否是合法的IP地址
  1456. *
  1457. * @param string $ip IP地址
  1458. * @param string $type IP地址类型 (ipv4, ipv6)
  1459. *
  1460. * @return boolean
  1461. */
  1462. public function isValidIP(string $ip, string $type = ''): bool
  1463. {
  1464. switch (strtolower($type)) {
  1465. case 'ipv4':
  1466. $flag = FILTER_FLAG_IPV4;
  1467. break;
  1468. case 'ipv6':
  1469. $flag = FILTER_FLAG_IPV6;
  1470. break;
  1471. default:
  1472. $flag = 0;
  1473. break;
  1474. }
  1475. return boolval(filter_var($ip, FILTER_VALIDATE_IP, $flag));
  1476. }
  1477. /**
  1478. * 将IP地址转换为二进制字符串
  1479. *
  1480. * @param string $ip
  1481. *
  1482. * @return string
  1483. */
  1484. public function ip2bin(string $ip): string
  1485. {
  1486. if ($this->isValidIP($ip, 'ipv6')) {
  1487. $IPHex = str_split(bin2hex(inet_pton($ip)), 4);
  1488. foreach ($IPHex as $key => $value) {
  1489. $IPHex[$key] = intval($value, 16);
  1490. }
  1491. $IPBin = vsprintf('%016b%016b%016b%016b%016b%016b%016b%016b', $IPHex);
  1492. } else {
  1493. $IPHex = str_split(bin2hex(inet_pton($ip)), 2);
  1494. foreach ($IPHex as $key => $value) {
  1495. $IPHex[$key] = intval($value, 16);
  1496. }
  1497. $IPBin = vsprintf('%08b%08b%08b%08b', $IPHex);
  1498. }
  1499. return $IPBin;
  1500. }
  1501. /**
  1502. * 检测是否使用手机访问
  1503. * @access public
  1504. * @return bool
  1505. */
  1506. public function isMobile(): bool
  1507. {
  1508. if ($this->server('HTTP_VIA') && stristr($this->server('HTTP_VIA'), "wap")) {
  1509. return true;
  1510. } elseif ($this->server('HTTP_ACCEPT') && strpos(strtoupper($this->server('HTTP_ACCEPT')), "VND.WAP.WML")) {
  1511. return true;
  1512. } elseif ($this->server('HTTP_X_WAP_PROFILE') || $this->server('HTTP_PROFILE')) {
  1513. return true;
  1514. } 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'))) {
  1515. return true;
  1516. }
  1517. return false;
  1518. }
  1519. /**
  1520. * 当前URL地址中的scheme参数
  1521. * @access public
  1522. * @return string
  1523. */
  1524. public function scheme(): string
  1525. {
  1526. return $this->isSsl() ? 'https' : 'http';
  1527. }
  1528. /**
  1529. * 当前请求URL地址中的query参数
  1530. * @access public
  1531. * @return string
  1532. */
  1533. public function query(): string
  1534. {
  1535. return $this->server('QUERY_STRING', '');
  1536. }
  1537. /**
  1538. * 设置当前请求的host(包含端口)
  1539. * @access public
  1540. * @param string $host 主机名(含端口)
  1541. * @return $this
  1542. */
  1543. public function setHost(string $host)
  1544. {
  1545. $this->host = $host;
  1546. return $this;
  1547. }
  1548. /**
  1549. * 当前请求的host
  1550. * @access public
  1551. * @param bool $strict true 仅仅获取HOST
  1552. * @return string
  1553. */
  1554. public function host(bool $strict = false): string
  1555. {
  1556. if ($this->host) {
  1557. $host = $this->host;
  1558. } else {
  1559. $host = strval($this->server('HTTP_X_FORWARDED_HOST') ?: $this->server('HTTP_HOST'));
  1560. }
  1561. return true === $strict && strpos($host, ':') ? strstr($host, ':', true) : $host;
  1562. }
  1563. /**
  1564. * 当前请求URL地址中的port参数
  1565. * @access public
  1566. * @return int
  1567. */
  1568. public function port(): int
  1569. {
  1570. return (int) ($this->server('HTTP_X_FORWARDED_PORT') ?: $this->server('SERVER_PORT', ''));
  1571. }
  1572. /**
  1573. * 当前请求 SERVER_PROTOCOL
  1574. * @access public
  1575. * @return string
  1576. */
  1577. public function protocol(): string
  1578. {
  1579. return $this->server('SERVER_PROTOCOL', '');
  1580. }
  1581. /**
  1582. * 当前请求 REMOTE_PORT
  1583. * @access public
  1584. * @return int
  1585. */
  1586. public function remotePort(): int
  1587. {
  1588. return (int) $this->server('REMOTE_PORT', '');
  1589. }
  1590. /**
  1591. * 当前请求 HTTP_CONTENT_TYPE
  1592. * @access public
  1593. * @return string
  1594. */
  1595. public function contentType(): string
  1596. {
  1597. $contentType = $this->header('Content-Type');
  1598. if ($contentType) {
  1599. if (strpos($contentType, ';')) {
  1600. [$type] = explode(';', $contentType);
  1601. } else {
  1602. $type = $contentType;
  1603. }
  1604. return trim($type);
  1605. }
  1606. return '';
  1607. }
  1608. /**
  1609. * 获取当前请求的安全Key
  1610. * @access public
  1611. * @return string
  1612. */
  1613. public function secureKey(): string
  1614. {
  1615. if (is_null($this->secureKey)) {
  1616. $this->secureKey = uniqid('', true);
  1617. }
  1618. return $this->secureKey;
  1619. }
  1620. /**
  1621. * 设置当前的控制器名
  1622. * @access public
  1623. * @param string $controller 控制器名
  1624. * @return $this
  1625. */
  1626. public function setController(string $controller)
  1627. {
  1628. $this->controller = $controller;
  1629. return $this;
  1630. }
  1631. /**
  1632. * 设置当前的操作名
  1633. * @access public
  1634. * @param string $action 操作名
  1635. * @return $this
  1636. */
  1637. public function setAction(string $action)
  1638. {
  1639. $this->action = $action;
  1640. return $this;
  1641. }
  1642. /**
  1643. * 获取当前的控制器名
  1644. * @access public
  1645. * @param bool $convert 转换为小写
  1646. * @return string
  1647. */
  1648. public function controller(bool $convert = false): string
  1649. {
  1650. $name = $this->controller ?: '';
  1651. return $convert ? strtolower($name) : $name;
  1652. }
  1653. /**
  1654. * 获取当前的操作名
  1655. * @access public
  1656. * @param bool $convert 转换为小写
  1657. * @return string
  1658. */
  1659. public function action(bool $convert = false): string
  1660. {
  1661. $name = $this->action ?: '';
  1662. return $convert ? strtolower($name) : $name;
  1663. }
  1664. /**
  1665. * 设置或者获取当前请求的content
  1666. * @access public
  1667. * @return string
  1668. */
  1669. public function getContent(): string
  1670. {
  1671. if (is_null($this->content)) {
  1672. $this->content = $this->input;
  1673. }
  1674. return $this->content;
  1675. }
  1676. /**
  1677. * 获取当前请求的php://input
  1678. * @access public
  1679. * @return string
  1680. */
  1681. public function getInput(): string
  1682. {
  1683. return $this->input;
  1684. }
  1685. /**
  1686. * 生成请求令牌
  1687. * @access public
  1688. * @param string $name 令牌名称
  1689. * @param mixed $type 令牌生成方法
  1690. * @return string
  1691. */
  1692. public function buildToken(string $name = '__token__', $type = 'md5'): string
  1693. {
  1694. $type = is_callable($type) ? $type : 'md5';
  1695. $token = call_user_func($type, $this->server('REQUEST_TIME_FLOAT'));
  1696. $this->session->set($name, $token);
  1697. return $token;
  1698. }
  1699. /**
  1700. * 检查请求令牌
  1701. * @access public
  1702. * @param string $token 令牌名称
  1703. * @param array $data 表单数据
  1704. * @return bool
  1705. */
  1706. public function checkToken(string $token = '__token__', array $data = []): bool
  1707. {
  1708. if (in_array($this->method(), ['GET', 'HEAD', 'OPTIONS'], true)) {
  1709. return true;
  1710. }
  1711. if (!$this->session->has($token)) {
  1712. // 令牌数据无效
  1713. return false;
  1714. }
  1715. // Header验证
  1716. if ($this->header('X-CSRF-TOKEN') && $this->session->get($token) === $this->header('X-CSRF-TOKEN')) {
  1717. // 防止重复提交
  1718. $this->session->delete($token); // 验证完成销毁session
  1719. return true;
  1720. }
  1721. if (empty($data)) {
  1722. $data = $this->post();
  1723. }
  1724. // 令牌验证
  1725. if (isset($data[$token]) && $this->session->get($token) === $data[$token]) {
  1726. // 防止重复提交
  1727. $this->session->delete($token); // 验证完成销毁session
  1728. return true;
  1729. }
  1730. // 开启TOKEN重置
  1731. $this->session->delete($token);
  1732. return false;
  1733. }
  1734. /**
  1735. * 设置在中间件传递的数据
  1736. * @access public
  1737. * @param array $middleware 数据
  1738. * @return $this
  1739. */
  1740. public function withMiddleware(array $middleware)
  1741. {
  1742. $this->middleware = array_merge($this->middleware, $middleware);
  1743. return $this;
  1744. }
  1745. /**
  1746. * 设置GET数据
  1747. * @access public
  1748. * @param array $get 数据
  1749. * @return $this
  1750. */
  1751. public function withGet(array $get)
  1752. {
  1753. $this->get = $get;
  1754. return $this;
  1755. }
  1756. /**
  1757. * 设置POST数据
  1758. * @access public
  1759. * @param array $post 数据
  1760. * @return $this
  1761. */
  1762. public function withPost(array $post)
  1763. {
  1764. $this->post = $post;
  1765. return $this;
  1766. }
  1767. /**
  1768. * 设置COOKIE数据
  1769. * @access public
  1770. * @param array $cookie 数据
  1771. * @return $this
  1772. */
  1773. public function withCookie(array $cookie)
  1774. {
  1775. $this->cookie = $cookie;
  1776. return $this;
  1777. }
  1778. /**
  1779. * 设置SESSION数据
  1780. * @access public
  1781. * @param Session $session 数据
  1782. * @return $this
  1783. */
  1784. public function withSession(Session $session)
  1785. {
  1786. $this->session = $session;
  1787. return $this;
  1788. }
  1789. /**
  1790. * 设置SERVER数据
  1791. * @access public
  1792. * @param array $server 数据
  1793. * @return $this
  1794. */
  1795. public function withServer(array $server)
  1796. {
  1797. $this->server = array_change_key_case($server, CASE_UPPER);
  1798. return $this;
  1799. }
  1800. /**
  1801. * 设置HEADER数据
  1802. * @access public
  1803. * @param array $header 数据
  1804. * @return $this
  1805. */
  1806. public function withHeader(array $header)
  1807. {
  1808. $this->header = array_change_key_case($header);
  1809. return $this;
  1810. }
  1811. /**
  1812. * 设置ENV数据
  1813. * @access public
  1814. * @param Env $env 数据
  1815. * @return $this
  1816. */
  1817. public function withEnv(Env $env)
  1818. {
  1819. $this->env = $env;
  1820. return $this;
  1821. }
  1822. /**
  1823. * 设置php://input数据
  1824. * @access public
  1825. * @param string $input RAW数据
  1826. * @return $this
  1827. */
  1828. public function withInput(string $input)
  1829. {
  1830. $this->input = $input;
  1831. if (!empty($input)) {
  1832. $inputData = $this->getInputData($input);
  1833. if (!empty($inputData)) {
  1834. $this->post = $inputData;
  1835. $this->put = $inputData;
  1836. }
  1837. }
  1838. return $this;
  1839. }
  1840. /**
  1841. * 设置文件上传数据
  1842. * @access public
  1843. * @param array $files 上传信息
  1844. * @return $this
  1845. */
  1846. public function withFiles(array $files)
  1847. {
  1848. $this->file = $files;
  1849. return $this;
  1850. }
  1851. /**
  1852. * 设置ROUTE变量
  1853. * @access public
  1854. * @param array $route 数据
  1855. * @return $this
  1856. */
  1857. public function withRoute(array $route)
  1858. {
  1859. $this->route = $route;
  1860. return $this;
  1861. }
  1862. /**
  1863. * 设置中间传递数据
  1864. * @access public
  1865. * @param string $name 参数名
  1866. * @param mixed $value 值
  1867. */
  1868. public function __set(string $name, $value)
  1869. {
  1870. $this->middleware[$name] = $value;
  1871. }
  1872. /**
  1873. * 获取中间传递数据的值
  1874. * @access public
  1875. * @param string $name 名称
  1876. * @return mixed
  1877. */
  1878. public function __get(string $name)
  1879. {
  1880. return $this->middleware($name);
  1881. }
  1882. /**
  1883. * 检测中间传递数据的值
  1884. * @access public
  1885. * @param string $name 名称
  1886. * @return boolean
  1887. */
  1888. public function __isset(string $name): bool
  1889. {
  1890. return isset($this->middleware[$name]);
  1891. }
  1892. // ArrayAccess
  1893. #[\ReturnTypeWillChange]
  1894. public function offsetExists($name): bool
  1895. {
  1896. return $this->has($name);
  1897. }
  1898. #[\ReturnTypeWillChange]
  1899. public function offsetGet($name)
  1900. {
  1901. return $this->param($name);
  1902. }
  1903. #[\ReturnTypeWillChange]
  1904. public function offsetSet($name, $value)
  1905. {}
  1906. #[\ReturnTypeWillChange]
  1907. public function offsetUnset($name)
  1908. {}
  1909. }