Request.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;
  12. use Symfony\Component\HttpFoundation\Exception\JsonException;
  13. use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
  14. use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
  15. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  16. // Help opcache.preload discover always-needed symbols
  17. class_exists(AcceptHeader::class);
  18. class_exists(FileBag::class);
  19. class_exists(HeaderBag::class);
  20. class_exists(HeaderUtils::class);
  21. class_exists(InputBag::class);
  22. class_exists(ParameterBag::class);
  23. class_exists(ServerBag::class);
  24. /**
  25. * Request represents an HTTP request.
  26. *
  27. * The methods dealing with URL accept / return a raw path (% encoded):
  28. * * getBasePath
  29. * * getBaseUrl
  30. * * getPathInfo
  31. * * getRequestUri
  32. * * getUri
  33. * * getUriForPath
  34. *
  35. * @author Fabien Potencier <fabien@symfony.com>
  36. */
  37. class Request
  38. {
  39. public const HEADER_FORWARDED = 0b000001; // When using RFC 7239
  40. public const HEADER_X_FORWARDED_FOR = 0b000010;
  41. public const HEADER_X_FORWARDED_HOST = 0b000100;
  42. public const HEADER_X_FORWARDED_PROTO = 0b001000;
  43. public const HEADER_X_FORWARDED_PORT = 0b010000;
  44. public const HEADER_X_FORWARDED_PREFIX = 0b100000;
  45. public const HEADER_X_FORWARDED_AWS_ELB = 0b0011010; // AWS ELB doesn't send X-Forwarded-Host
  46. public const HEADER_X_FORWARDED_TRAEFIK = 0b0111110; // All "X-Forwarded-*" headers sent by Traefik reverse proxy
  47. public const METHOD_HEAD = 'HEAD';
  48. public const METHOD_GET = 'GET';
  49. public const METHOD_POST = 'POST';
  50. public const METHOD_PUT = 'PUT';
  51. public const METHOD_PATCH = 'PATCH';
  52. public const METHOD_DELETE = 'DELETE';
  53. public const METHOD_PURGE = 'PURGE';
  54. public const METHOD_OPTIONS = 'OPTIONS';
  55. public const METHOD_TRACE = 'TRACE';
  56. public const METHOD_CONNECT = 'CONNECT';
  57. /**
  58. * @var string[]
  59. */
  60. protected static $trustedProxies = [];
  61. /**
  62. * @var string[]
  63. */
  64. protected static $trustedHostPatterns = [];
  65. /**
  66. * @var string[]
  67. */
  68. protected static $trustedHosts = [];
  69. protected static $httpMethodParameterOverride = false;
  70. /**
  71. * Custom parameters.
  72. *
  73. * @var ParameterBag
  74. */
  75. public $attributes;
  76. /**
  77. * Request body parameters ($_POST).
  78. *
  79. * @var InputBag
  80. */
  81. public $request;
  82. /**
  83. * Query string parameters ($_GET).
  84. *
  85. * @var InputBag
  86. */
  87. public $query;
  88. /**
  89. * Server and execution environment parameters ($_SERVER).
  90. *
  91. * @var ServerBag
  92. */
  93. public $server;
  94. /**
  95. * Uploaded files ($_FILES).
  96. *
  97. * @var FileBag
  98. */
  99. public $files;
  100. /**
  101. * Cookies ($_COOKIE).
  102. *
  103. * @var InputBag
  104. */
  105. public $cookies;
  106. /**
  107. * Headers (taken from the $_SERVER).
  108. *
  109. * @var HeaderBag
  110. */
  111. public $headers;
  112. /**
  113. * @var string|resource|false|null
  114. */
  115. protected $content;
  116. /**
  117. * @var array
  118. */
  119. protected $languages;
  120. /**
  121. * @var array
  122. */
  123. protected $charsets;
  124. /**
  125. * @var array
  126. */
  127. protected $encodings;
  128. /**
  129. * @var array
  130. */
  131. protected $acceptableContentTypes;
  132. /**
  133. * @var string
  134. */
  135. protected $pathInfo;
  136. /**
  137. * @var string
  138. */
  139. protected $requestUri;
  140. /**
  141. * @var string
  142. */
  143. protected $baseUrl;
  144. /**
  145. * @var string
  146. */
  147. protected $basePath;
  148. /**
  149. * @var string
  150. */
  151. protected $method;
  152. /**
  153. * @var string
  154. */
  155. protected $format;
  156. /**
  157. * @var SessionInterface|callable(): SessionInterface
  158. */
  159. protected $session;
  160. /**
  161. * @var string
  162. */
  163. protected $locale;
  164. /**
  165. * @var string
  166. */
  167. protected $defaultLocale = 'en';
  168. /**
  169. * @var array
  170. */
  171. protected static $formats;
  172. protected static $requestFactory;
  173. private ?string $preferredFormat = null;
  174. private bool $isHostValid = true;
  175. private bool $isForwardedValid = true;
  176. private bool $isSafeContentPreferred;
  177. private static int $trustedHeaderSet = -1;
  178. private const FORWARDED_PARAMS = [
  179. self::HEADER_X_FORWARDED_FOR => 'for',
  180. self::HEADER_X_FORWARDED_HOST => 'host',
  181. self::HEADER_X_FORWARDED_PROTO => 'proto',
  182. self::HEADER_X_FORWARDED_PORT => 'host',
  183. ];
  184. /**
  185. * Names for headers that can be trusted when
  186. * using trusted proxies.
  187. *
  188. * The FORWARDED header is the standard as of rfc7239.
  189. *
  190. * The other headers are non-standard, but widely used
  191. * by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
  192. */
  193. private const TRUSTED_HEADERS = [
  194. self::HEADER_FORWARDED => 'FORWARDED',
  195. self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
  196. self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
  197. self::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
  198. self::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
  199. self::HEADER_X_FORWARDED_PREFIX => 'X_FORWARDED_PREFIX',
  200. ];
  201. /**
  202. * @param array $query The GET parameters
  203. * @param array $request The POST parameters
  204. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  205. * @param array $cookies The COOKIE parameters
  206. * @param array $files The FILES parameters
  207. * @param array $server The SERVER parameters
  208. * @param string|resource|null $content The raw body data
  209. */
  210. public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null)
  211. {
  212. $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
  213. }
  214. /**
  215. * Sets the parameters for this request.
  216. *
  217. * This method also re-initializes all properties.
  218. *
  219. * @param array $query The GET parameters
  220. * @param array $request The POST parameters
  221. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  222. * @param array $cookies The COOKIE parameters
  223. * @param array $files The FILES parameters
  224. * @param array $server The SERVER parameters
  225. * @param string|resource|null $content The raw body data
  226. */
  227. public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null)
  228. {
  229. $this->request = new InputBag($request);
  230. $this->query = new InputBag($query);
  231. $this->attributes = new ParameterBag($attributes);
  232. $this->cookies = new InputBag($cookies);
  233. $this->files = new FileBag($files);
  234. $this->server = new ServerBag($server);
  235. $this->headers = new HeaderBag($this->server->getHeaders());
  236. $this->content = $content;
  237. $this->languages = null;
  238. $this->charsets = null;
  239. $this->encodings = null;
  240. $this->acceptableContentTypes = null;
  241. $this->pathInfo = null;
  242. $this->requestUri = null;
  243. $this->baseUrl = null;
  244. $this->basePath = null;
  245. $this->method = null;
  246. $this->format = null;
  247. }
  248. /**
  249. * Creates a new request with values from PHP's super globals.
  250. */
  251. public static function createFromGlobals(): static
  252. {
  253. $request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER);
  254. if (str_starts_with($request->headers->get('CONTENT_TYPE', ''), 'application/x-www-form-urlencoded')
  255. && \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), ['PUT', 'DELETE', 'PATCH'])
  256. ) {
  257. parse_str($request->getContent(), $data);
  258. $request->request = new InputBag($data);
  259. }
  260. return $request;
  261. }
  262. /**
  263. * Creates a Request based on a given URI and configuration.
  264. *
  265. * The information contained in the URI always take precedence
  266. * over the other information (server and parameters).
  267. *
  268. * @param string $uri The URI
  269. * @param string $method The HTTP method
  270. * @param array $parameters The query (GET) or request (POST) parameters
  271. * @param array $cookies The request cookies ($_COOKIE)
  272. * @param array $files The request files ($_FILES)
  273. * @param array $server The server parameters ($_SERVER)
  274. * @param string|resource|null $content The raw body data
  275. */
  276. public static function create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content = null): static
  277. {
  278. $server = array_replace([
  279. 'SERVER_NAME' => 'localhost',
  280. 'SERVER_PORT' => 80,
  281. 'HTTP_HOST' => 'localhost',
  282. 'HTTP_USER_AGENT' => 'Symfony',
  283. 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  284. 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
  285. 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  286. 'REMOTE_ADDR' => '127.0.0.1',
  287. 'SCRIPT_NAME' => '',
  288. 'SCRIPT_FILENAME' => '',
  289. 'SERVER_PROTOCOL' => 'HTTP/1.1',
  290. 'REQUEST_TIME' => time(),
  291. 'REQUEST_TIME_FLOAT' => microtime(true),
  292. ], $server);
  293. $server['PATH_INFO'] = '';
  294. $server['REQUEST_METHOD'] = strtoupper($method);
  295. $components = parse_url($uri);
  296. if (isset($components['host'])) {
  297. $server['SERVER_NAME'] = $components['host'];
  298. $server['HTTP_HOST'] = $components['host'];
  299. }
  300. if (isset($components['scheme'])) {
  301. if ('https' === $components['scheme']) {
  302. $server['HTTPS'] = 'on';
  303. $server['SERVER_PORT'] = 443;
  304. } else {
  305. unset($server['HTTPS']);
  306. $server['SERVER_PORT'] = 80;
  307. }
  308. }
  309. if (isset($components['port'])) {
  310. $server['SERVER_PORT'] = $components['port'];
  311. $server['HTTP_HOST'] .= ':'.$components['port'];
  312. }
  313. if (isset($components['user'])) {
  314. $server['PHP_AUTH_USER'] = $components['user'];
  315. }
  316. if (isset($components['pass'])) {
  317. $server['PHP_AUTH_PW'] = $components['pass'];
  318. }
  319. if (!isset($components['path'])) {
  320. $components['path'] = '/';
  321. }
  322. switch (strtoupper($method)) {
  323. case 'POST':
  324. case 'PUT':
  325. case 'DELETE':
  326. if (!isset($server['CONTENT_TYPE'])) {
  327. $server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  328. }
  329. // no break
  330. case 'PATCH':
  331. $request = $parameters;
  332. $query = [];
  333. break;
  334. default:
  335. $request = [];
  336. $query = $parameters;
  337. break;
  338. }
  339. $queryString = '';
  340. if (isset($components['query'])) {
  341. parse_str(html_entity_decode($components['query']), $qs);
  342. if ($query) {
  343. $query = array_replace($qs, $query);
  344. $queryString = http_build_query($query, '', '&');
  345. } else {
  346. $query = $qs;
  347. $queryString = $components['query'];
  348. }
  349. } elseif ($query) {
  350. $queryString = http_build_query($query, '', '&');
  351. }
  352. $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : '');
  353. $server['QUERY_STRING'] = $queryString;
  354. return self::createRequestFromFactory($query, $request, [], $cookies, $files, $server, $content);
  355. }
  356. /**
  357. * Sets a callable able to create a Request instance.
  358. *
  359. * This is mainly useful when you need to override the Request class
  360. * to keep BC with an existing system. It should not be used for any
  361. * other purpose.
  362. */
  363. public static function setFactory(?callable $callable)
  364. {
  365. self::$requestFactory = $callable;
  366. }
  367. /**
  368. * Clones a request and overrides some of its parameters.
  369. *
  370. * @param array $query The GET parameters
  371. * @param array $request The POST parameters
  372. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  373. * @param array $cookies The COOKIE parameters
  374. * @param array $files The FILES parameters
  375. * @param array $server The SERVER parameters
  376. */
  377. public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null): static
  378. {
  379. $dup = clone $this;
  380. if (null !== $query) {
  381. $dup->query = new InputBag($query);
  382. }
  383. if (null !== $request) {
  384. $dup->request = new InputBag($request);
  385. }
  386. if (null !== $attributes) {
  387. $dup->attributes = new ParameterBag($attributes);
  388. }
  389. if (null !== $cookies) {
  390. $dup->cookies = new InputBag($cookies);
  391. }
  392. if (null !== $files) {
  393. $dup->files = new FileBag($files);
  394. }
  395. if (null !== $server) {
  396. $dup->server = new ServerBag($server);
  397. $dup->headers = new HeaderBag($dup->server->getHeaders());
  398. }
  399. $dup->languages = null;
  400. $dup->charsets = null;
  401. $dup->encodings = null;
  402. $dup->acceptableContentTypes = null;
  403. $dup->pathInfo = null;
  404. $dup->requestUri = null;
  405. $dup->baseUrl = null;
  406. $dup->basePath = null;
  407. $dup->method = null;
  408. $dup->format = null;
  409. if (!$dup->get('_format') && $this->get('_format')) {
  410. $dup->attributes->set('_format', $this->get('_format'));
  411. }
  412. if (!$dup->getRequestFormat(null)) {
  413. $dup->setRequestFormat($this->getRequestFormat(null));
  414. }
  415. return $dup;
  416. }
  417. /**
  418. * Clones the current request.
  419. *
  420. * Note that the session is not cloned as duplicated requests
  421. * are most of the time sub-requests of the main one.
  422. */
  423. public function __clone()
  424. {
  425. $this->query = clone $this->query;
  426. $this->request = clone $this->request;
  427. $this->attributes = clone $this->attributes;
  428. $this->cookies = clone $this->cookies;
  429. $this->files = clone $this->files;
  430. $this->server = clone $this->server;
  431. $this->headers = clone $this->headers;
  432. }
  433. public function __toString(): string
  434. {
  435. $content = $this->getContent();
  436. $cookieHeader = '';
  437. $cookies = [];
  438. foreach ($this->cookies as $k => $v) {
  439. $cookies[] = \is_array($v) ? http_build_query([$k => $v], '', '; ', \PHP_QUERY_RFC3986) : "$k=$v";
  440. }
  441. if ($cookies) {
  442. $cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
  443. }
  444. return
  445. sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
  446. $this->headers.
  447. $cookieHeader."\r\n".
  448. $content;
  449. }
  450. /**
  451. * Overrides the PHP global variables according to this request instance.
  452. *
  453. * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE.
  454. * $_FILES is never overridden, see rfc1867
  455. */
  456. public function overrideGlobals()
  457. {
  458. $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '', '&')));
  459. $_GET = $this->query->all();
  460. $_POST = $this->request->all();
  461. $_SERVER = $this->server->all();
  462. $_COOKIE = $this->cookies->all();
  463. foreach ($this->headers->all() as $key => $value) {
  464. $key = strtoupper(str_replace('-', '_', $key));
  465. if (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH', 'CONTENT_MD5'], true)) {
  466. $_SERVER[$key] = implode(', ', $value);
  467. } else {
  468. $_SERVER['HTTP_'.$key] = implode(', ', $value);
  469. }
  470. }
  471. $request = ['g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE];
  472. $requestOrder = \ini_get('request_order') ?: \ini_get('variables_order');
  473. $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp';
  474. $_REQUEST = [[]];
  475. foreach (str_split($requestOrder) as $order) {
  476. $_REQUEST[] = $request[$order];
  477. }
  478. $_REQUEST = array_merge(...$_REQUEST);
  479. }
  480. /**
  481. * Sets a list of trusted proxies.
  482. *
  483. * You should only list the reverse proxies that you manage directly.
  484. *
  485. * @param array $proxies A list of trusted proxies, the string 'REMOTE_ADDR' will be replaced with $_SERVER['REMOTE_ADDR']
  486. * @param int $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies
  487. */
  488. public static function setTrustedProxies(array $proxies, int $trustedHeaderSet)
  489. {
  490. self::$trustedProxies = array_reduce($proxies, function ($proxies, $proxy) {
  491. if ('REMOTE_ADDR' !== $proxy) {
  492. $proxies[] = $proxy;
  493. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  494. $proxies[] = $_SERVER['REMOTE_ADDR'];
  495. }
  496. return $proxies;
  497. }, []);
  498. self::$trustedHeaderSet = $trustedHeaderSet;
  499. }
  500. /**
  501. * Gets the list of trusted proxies.
  502. */
  503. public static function getTrustedProxies(): array
  504. {
  505. return self::$trustedProxies;
  506. }
  507. /**
  508. * Gets the set of trusted headers from trusted proxies.
  509. *
  510. * @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies
  511. */
  512. public static function getTrustedHeaderSet(): int
  513. {
  514. return self::$trustedHeaderSet;
  515. }
  516. /**
  517. * Sets a list of trusted host patterns.
  518. *
  519. * You should only list the hosts you manage using regexs.
  520. *
  521. * @param array $hostPatterns A list of trusted host patterns
  522. */
  523. public static function setTrustedHosts(array $hostPatterns)
  524. {
  525. self::$trustedHostPatterns = array_map(function ($hostPattern) {
  526. return sprintf('{%s}i', $hostPattern);
  527. }, $hostPatterns);
  528. // we need to reset trusted hosts on trusted host patterns change
  529. self::$trustedHosts = [];
  530. }
  531. /**
  532. * Gets the list of trusted host patterns.
  533. */
  534. public static function getTrustedHosts(): array
  535. {
  536. return self::$trustedHostPatterns;
  537. }
  538. /**
  539. * Normalizes a query string.
  540. *
  541. * It builds a normalized query string, where keys/value pairs are alphabetized,
  542. * have consistent escaping and unneeded delimiters are removed.
  543. */
  544. public static function normalizeQueryString(?string $qs): string
  545. {
  546. if ('' === ($qs ?? '')) {
  547. return '';
  548. }
  549. $qs = HeaderUtils::parseQuery($qs);
  550. ksort($qs);
  551. return http_build_query($qs, '', '&', \PHP_QUERY_RFC3986);
  552. }
  553. /**
  554. * Enables support for the _method request parameter to determine the intended HTTP method.
  555. *
  556. * Be warned that enabling this feature might lead to CSRF issues in your code.
  557. * Check that you are using CSRF tokens when required.
  558. * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered
  559. * and used to send a "PUT" or "DELETE" request via the _method request parameter.
  560. * If these methods are not protected against CSRF, this presents a possible vulnerability.
  561. *
  562. * The HTTP method can only be overridden when the real HTTP method is POST.
  563. */
  564. public static function enableHttpMethodParameterOverride()
  565. {
  566. self::$httpMethodParameterOverride = true;
  567. }
  568. /**
  569. * Checks whether support for the _method request parameter is enabled.
  570. */
  571. public static function getHttpMethodParameterOverride(): bool
  572. {
  573. return self::$httpMethodParameterOverride;
  574. }
  575. /**
  576. * Gets a "parameter" value from any bag.
  577. *
  578. * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the
  579. * flexibility in controllers, it is better to explicitly get request parameters from the appropriate
  580. * public property instead (attributes, query, request).
  581. *
  582. * Order of precedence: PATH (routing placeholders or custom attributes), GET, POST
  583. *
  584. * @internal use explicit input sources instead
  585. */
  586. public function get(string $key, mixed $default = null): mixed
  587. {
  588. if ($this !== $result = $this->attributes->get($key, $this)) {
  589. return $result;
  590. }
  591. if ($this->query->has($key)) {
  592. return $this->query->all()[$key];
  593. }
  594. if ($this->request->has($key)) {
  595. return $this->request->all()[$key];
  596. }
  597. return $default;
  598. }
  599. /**
  600. * Gets the Session.
  601. */
  602. public function getSession(): SessionInterface
  603. {
  604. $session = $this->session;
  605. if (!$session instanceof SessionInterface && null !== $session) {
  606. $this->setSession($session = $session());
  607. }
  608. if (null === $session) {
  609. throw new SessionNotFoundException('Session has not been set.');
  610. }
  611. return $session;
  612. }
  613. /**
  614. * Whether the request contains a Session which was started in one of the
  615. * previous requests.
  616. */
  617. public function hasPreviousSession(): bool
  618. {
  619. // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
  620. return $this->hasSession() && $this->cookies->has($this->getSession()->getName());
  621. }
  622. /**
  623. * Whether the request contains a Session object.
  624. *
  625. * This method does not give any information about the state of the session object,
  626. * like whether the session is started or not. It is just a way to check if this Request
  627. * is associated with a Session instance.
  628. *
  629. * @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory`
  630. */
  631. public function hasSession(bool $skipIfUninitialized = false): bool
  632. {
  633. return null !== $this->session && (!$skipIfUninitialized || $this->session instanceof SessionInterface);
  634. }
  635. public function setSession(SessionInterface $session)
  636. {
  637. $this->session = $session;
  638. }
  639. /**
  640. * @internal
  641. *
  642. * @param callable(): SessionInterface $factory
  643. */
  644. public function setSessionFactory(callable $factory)
  645. {
  646. $this->session = $factory;
  647. }
  648. /**
  649. * Returns the client IP addresses.
  650. *
  651. * In the returned array the most trusted IP address is first, and the
  652. * least trusted one last. The "real" client IP address is the last one,
  653. * but this is also the least trusted one. Trusted proxies are stripped.
  654. *
  655. * Use this method carefully; you should use getClientIp() instead.
  656. *
  657. * @see getClientIp()
  658. */
  659. public function getClientIps(): array
  660. {
  661. $ip = $this->server->get('REMOTE_ADDR');
  662. if (!$this->isFromTrustedProxy()) {
  663. return [$ip];
  664. }
  665. return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR, $ip) ?: [$ip];
  666. }
  667. /**
  668. * Returns the client IP address.
  669. *
  670. * This method can read the client IP address from the "X-Forwarded-For" header
  671. * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
  672. * header value is a comma+space separated list of IP addresses, the left-most
  673. * being the original client, and each successive proxy that passed the request
  674. * adding the IP address where it received the request from.
  675. *
  676. * If your reverse proxy uses a different header name than "X-Forwarded-For",
  677. * ("Client-Ip" for instance), configure it via the $trustedHeaderSet
  678. * argument of the Request::setTrustedProxies() method instead.
  679. *
  680. * @see getClientIps()
  681. * @see https://wikipedia.org/wiki/X-Forwarded-For
  682. */
  683. public function getClientIp(): ?string
  684. {
  685. $ipAddresses = $this->getClientIps();
  686. return $ipAddresses[0];
  687. }
  688. /**
  689. * Returns current script name.
  690. */
  691. public function getScriptName(): string
  692. {
  693. return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
  694. }
  695. /**
  696. * Returns the path being requested relative to the executed script.
  697. *
  698. * The path info always starts with a /.
  699. *
  700. * Suppose this request is instantiated from /mysite on localhost:
  701. *
  702. * * http://localhost/mysite returns an empty string
  703. * * http://localhost/mysite/about returns '/about'
  704. * * http://localhost/mysite/enco%20ded returns '/enco%20ded'
  705. * * http://localhost/mysite/about?var=1 returns '/about'
  706. *
  707. * @return string The raw path (i.e. not urldecoded)
  708. */
  709. public function getPathInfo(): string
  710. {
  711. if (null === $this->pathInfo) {
  712. $this->pathInfo = $this->preparePathInfo();
  713. }
  714. return $this->pathInfo;
  715. }
  716. /**
  717. * Returns the root path from which this request is executed.
  718. *
  719. * Suppose that an index.php file instantiates this request object:
  720. *
  721. * * http://localhost/index.php returns an empty string
  722. * * http://localhost/index.php/page returns an empty string
  723. * * http://localhost/web/index.php returns '/web'
  724. * * http://localhost/we%20b/index.php returns '/we%20b'
  725. *
  726. * @return string The raw path (i.e. not urldecoded)
  727. */
  728. public function getBasePath(): string
  729. {
  730. if (null === $this->basePath) {
  731. $this->basePath = $this->prepareBasePath();
  732. }
  733. return $this->basePath;
  734. }
  735. /**
  736. * Returns the root URL from which this request is executed.
  737. *
  738. * The base URL never ends with a /.
  739. *
  740. * This is similar to getBasePath(), except that it also includes the
  741. * script filename (e.g. index.php) if one exists.
  742. *
  743. * @return string The raw URL (i.e. not urldecoded)
  744. */
  745. public function getBaseUrl(): string
  746. {
  747. $trustedPrefix = '';
  748. // the proxy prefix must be prepended to any prefix being needed at the webserver level
  749. if ($this->isFromTrustedProxy() && $trustedPrefixValues = $this->getTrustedValues(self::HEADER_X_FORWARDED_PREFIX)) {
  750. $trustedPrefix = rtrim($trustedPrefixValues[0], '/');
  751. }
  752. return $trustedPrefix.$this->getBaseUrlReal();
  753. }
  754. /**
  755. * Returns the real base URL received by the webserver from which this request is executed.
  756. * The URL does not include trusted reverse proxy prefix.
  757. *
  758. * @return string The raw URL (i.e. not urldecoded)
  759. */
  760. private function getBaseUrlReal(): string
  761. {
  762. if (null === $this->baseUrl) {
  763. $this->baseUrl = $this->prepareBaseUrl();
  764. }
  765. return $this->baseUrl;
  766. }
  767. /**
  768. * Gets the request's scheme.
  769. */
  770. public function getScheme(): string
  771. {
  772. return $this->isSecure() ? 'https' : 'http';
  773. }
  774. /**
  775. * Returns the port on which the request is made.
  776. *
  777. * This method can read the client port from the "X-Forwarded-Port" header
  778. * when trusted proxies were set via "setTrustedProxies()".
  779. *
  780. * The "X-Forwarded-Port" header must contain the client port.
  781. *
  782. * @return int|string|null Can be a string if fetched from the server bag
  783. */
  784. public function getPort(): int|string|null
  785. {
  786. if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_PORT)) {
  787. $host = $host[0];
  788. } elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) {
  789. $host = $host[0];
  790. } elseif (!$host = $this->headers->get('HOST')) {
  791. return $this->server->get('SERVER_PORT');
  792. }
  793. if ('[' === $host[0]) {
  794. $pos = strpos($host, ':', strrpos($host, ']'));
  795. } else {
  796. $pos = strrpos($host, ':');
  797. }
  798. if (false !== $pos && $port = substr($host, $pos + 1)) {
  799. return (int) $port;
  800. }
  801. return 'https' === $this->getScheme() ? 443 : 80;
  802. }
  803. /**
  804. * Returns the user.
  805. */
  806. public function getUser(): ?string
  807. {
  808. return $this->headers->get('PHP_AUTH_USER');
  809. }
  810. /**
  811. * Returns the password.
  812. */
  813. public function getPassword(): ?string
  814. {
  815. return $this->headers->get('PHP_AUTH_PW');
  816. }
  817. /**
  818. * Gets the user info.
  819. *
  820. * @return string|null A user name if any and, optionally, scheme-specific information about how to gain authorization to access the server
  821. */
  822. public function getUserInfo(): ?string
  823. {
  824. $userinfo = $this->getUser();
  825. $pass = $this->getPassword();
  826. if ('' != $pass) {
  827. $userinfo .= ":$pass";
  828. }
  829. return $userinfo;
  830. }
  831. /**
  832. * Returns the HTTP host being requested.
  833. *
  834. * The port name will be appended to the host if it's non-standard.
  835. */
  836. public function getHttpHost(): string
  837. {
  838. $scheme = $this->getScheme();
  839. $port = $this->getPort();
  840. if (('http' == $scheme && 80 == $port) || ('https' == $scheme && 443 == $port)) {
  841. return $this->getHost();
  842. }
  843. return $this->getHost().':'.$port;
  844. }
  845. /**
  846. * Returns the requested URI (path and query string).
  847. *
  848. * @return string The raw URI (i.e. not URI decoded)
  849. */
  850. public function getRequestUri(): string
  851. {
  852. if (null === $this->requestUri) {
  853. $this->requestUri = $this->prepareRequestUri();
  854. }
  855. return $this->requestUri;
  856. }
  857. /**
  858. * Gets the scheme and HTTP host.
  859. *
  860. * If the URL was called with basic authentication, the user
  861. * and the password are not added to the generated string.
  862. */
  863. public function getSchemeAndHttpHost(): string
  864. {
  865. return $this->getScheme().'://'.$this->getHttpHost();
  866. }
  867. /**
  868. * Generates a normalized URI (URL) for the Request.
  869. *
  870. * @see getQueryString()
  871. */
  872. public function getUri(): string
  873. {
  874. if (null !== $qs = $this->getQueryString()) {
  875. $qs = '?'.$qs;
  876. }
  877. return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
  878. }
  879. /**
  880. * Generates a normalized URI for the given path.
  881. *
  882. * @param string $path A path to use instead of the current one
  883. */
  884. public function getUriForPath(string $path): string
  885. {
  886. return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
  887. }
  888. /**
  889. * Returns the path as relative reference from the current Request path.
  890. *
  891. * Only the URIs path component (no schema, host etc.) is relevant and must be given.
  892. * Both paths must be absolute and not contain relative parts.
  893. * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
  894. * Furthermore, they can be used to reduce the link size in documents.
  895. *
  896. * Example target paths, given a base path of "/a/b/c/d":
  897. * - "/a/b/c/d" -> ""
  898. * - "/a/b/c/" -> "./"
  899. * - "/a/b/" -> "../"
  900. * - "/a/b/c/other" -> "other"
  901. * - "/a/x/y" -> "../../x/y"
  902. */
  903. public function getRelativeUriForPath(string $path): string
  904. {
  905. // be sure that we are dealing with an absolute path
  906. if (!isset($path[0]) || '/' !== $path[0]) {
  907. return $path;
  908. }
  909. if ($path === $basePath = $this->getPathInfo()) {
  910. return '';
  911. }
  912. $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
  913. $targetDirs = explode('/', substr($path, 1));
  914. array_pop($sourceDirs);
  915. $targetFile = array_pop($targetDirs);
  916. foreach ($sourceDirs as $i => $dir) {
  917. if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
  918. unset($sourceDirs[$i], $targetDirs[$i]);
  919. } else {
  920. break;
  921. }
  922. }
  923. $targetDirs[] = $targetFile;
  924. $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs);
  925. // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
  926. // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  927. // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
  928. // (see https://tools.ietf.org/html/rfc3986#section-4.2).
  929. return !isset($path[0]) || '/' === $path[0]
  930. || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
  931. ? "./$path" : $path;
  932. }
  933. /**
  934. * Generates the normalized query string for the Request.
  935. *
  936. * It builds a normalized query string, where keys/value pairs are alphabetized
  937. * and have consistent escaping.
  938. */
  939. public function getQueryString(): ?string
  940. {
  941. $qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
  942. return '' === $qs ? null : $qs;
  943. }
  944. /**
  945. * Checks whether the request is secure or not.
  946. *
  947. * This method can read the client protocol from the "X-Forwarded-Proto" header
  948. * when trusted proxies were set via "setTrustedProxies()".
  949. *
  950. * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
  951. */
  952. public function isSecure(): bool
  953. {
  954. if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) {
  955. return \in_array(strtolower($proto[0]), ['https', 'on', 'ssl', '1'], true);
  956. }
  957. $https = $this->server->get('HTTPS');
  958. return !empty($https) && 'off' !== strtolower($https);
  959. }
  960. /**
  961. * Returns the host name.
  962. *
  963. * This method can read the client host name from the "X-Forwarded-Host" header
  964. * when trusted proxies were set via "setTrustedProxies()".
  965. *
  966. * The "X-Forwarded-Host" header must contain the client host name.
  967. *
  968. * @throws SuspiciousOperationException when the host name is invalid or not trusted
  969. */
  970. public function getHost(): string
  971. {
  972. if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) {
  973. $host = $host[0];
  974. } elseif (!$host = $this->headers->get('HOST')) {
  975. if (!$host = $this->server->get('SERVER_NAME')) {
  976. $host = $this->server->get('SERVER_ADDR', '');
  977. }
  978. }
  979. // trim and remove port number from host
  980. // host is lowercase as per RFC 952/2181
  981. $host = strtolower(preg_replace('/:\d+$/', '', trim($host)));
  982. // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
  983. // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
  984. // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
  985. if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
  986. if (!$this->isHostValid) {
  987. return '';
  988. }
  989. $this->isHostValid = false;
  990. throw new SuspiciousOperationException(sprintf('Invalid Host "%s".', $host));
  991. }
  992. if (\count(self::$trustedHostPatterns) > 0) {
  993. // to avoid host header injection attacks, you should provide a list of trusted host patterns
  994. if (\in_array($host, self::$trustedHosts)) {
  995. return $host;
  996. }
  997. foreach (self::$trustedHostPatterns as $pattern) {
  998. if (preg_match($pattern, $host)) {
  999. self::$trustedHosts[] = $host;
  1000. return $host;
  1001. }
  1002. }
  1003. if (!$this->isHostValid) {
  1004. return '';
  1005. }
  1006. $this->isHostValid = false;
  1007. throw new SuspiciousOperationException(sprintf('Untrusted Host "%s".', $host));
  1008. }
  1009. return $host;
  1010. }
  1011. /**
  1012. * Sets the request method.
  1013. */
  1014. public function setMethod(string $method)
  1015. {
  1016. $this->method = null;
  1017. $this->server->set('REQUEST_METHOD', $method);
  1018. }
  1019. /**
  1020. * Gets the request "intended" method.
  1021. *
  1022. * If the X-HTTP-Method-Override header is set, and if the method is a POST,
  1023. * then it is used to determine the "real" intended HTTP method.
  1024. *
  1025. * The _method request parameter can also be used to determine the HTTP method,
  1026. * but only if enableHttpMethodParameterOverride() has been called.
  1027. *
  1028. * The method is always an uppercased string.
  1029. *
  1030. * @see getRealMethod()
  1031. */
  1032. public function getMethod(): string
  1033. {
  1034. if (null !== $this->method) {
  1035. return $this->method;
  1036. }
  1037. $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  1038. if ('POST' !== $this->method) {
  1039. return $this->method;
  1040. }
  1041. $method = $this->headers->get('X-HTTP-METHOD-OVERRIDE');
  1042. if (!$method && self::$httpMethodParameterOverride) {
  1043. $method = $this->request->get('_method', $this->query->get('_method', 'POST'));
  1044. }
  1045. if (!\is_string($method)) {
  1046. return $this->method;
  1047. }
  1048. $method = strtoupper($method);
  1049. if (\in_array($method, ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH', 'PURGE', 'TRACE'], true)) {
  1050. return $this->method = $method;
  1051. }
  1052. if (!preg_match('/^[A-Z]++$/D', $method)) {
  1053. throw new SuspiciousOperationException(sprintf('Invalid method override "%s".', $method));
  1054. }
  1055. return $this->method = $method;
  1056. }
  1057. /**
  1058. * Gets the "real" request method.
  1059. *
  1060. * @see getMethod()
  1061. */
  1062. public function getRealMethod(): string
  1063. {
  1064. return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  1065. }
  1066. /**
  1067. * Gets the mime type associated with the format.
  1068. */
  1069. public function getMimeType(string $format): ?string
  1070. {
  1071. if (null === static::$formats) {
  1072. static::initializeFormats();
  1073. }
  1074. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  1075. }
  1076. /**
  1077. * Gets the mime types associated with the format.
  1078. */
  1079. public static function getMimeTypes(string $format): array
  1080. {
  1081. if (null === static::$formats) {
  1082. static::initializeFormats();
  1083. }
  1084. return static::$formats[$format] ?? [];
  1085. }
  1086. /**
  1087. * Gets the format associated with the mime type.
  1088. */
  1089. public function getFormat(?string $mimeType): ?string
  1090. {
  1091. $canonicalMimeType = null;
  1092. if ($mimeType && false !== $pos = strpos($mimeType, ';')) {
  1093. $canonicalMimeType = trim(substr($mimeType, 0, $pos));
  1094. }
  1095. if (null === static::$formats) {
  1096. static::initializeFormats();
  1097. }
  1098. foreach (static::$formats as $format => $mimeTypes) {
  1099. if (\in_array($mimeType, (array) $mimeTypes)) {
  1100. return $format;
  1101. }
  1102. if (null !== $canonicalMimeType && \in_array($canonicalMimeType, (array) $mimeTypes)) {
  1103. return $format;
  1104. }
  1105. }
  1106. return null;
  1107. }
  1108. /**
  1109. * Associates a format with mime types.
  1110. *
  1111. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  1112. */
  1113. public function setFormat(?string $format, string|array $mimeTypes)
  1114. {
  1115. if (null === static::$formats) {
  1116. static::initializeFormats();
  1117. }
  1118. static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : [$mimeTypes];
  1119. }
  1120. /**
  1121. * Gets the request format.
  1122. *
  1123. * Here is the process to determine the format:
  1124. *
  1125. * * format defined by the user (with setRequestFormat())
  1126. * * _format request attribute
  1127. * * $default
  1128. *
  1129. * @see getPreferredFormat
  1130. */
  1131. public function getRequestFormat(?string $default = 'html'): ?string
  1132. {
  1133. if (null === $this->format) {
  1134. $this->format = $this->attributes->get('_format');
  1135. }
  1136. return $this->format ?? $default;
  1137. }
  1138. /**
  1139. * Sets the request format.
  1140. */
  1141. public function setRequestFormat(?string $format)
  1142. {
  1143. $this->format = $format;
  1144. }
  1145. /**
  1146. * Gets the format associated with the request.
  1147. */
  1148. public function getContentType(): ?string
  1149. {
  1150. return $this->getFormat($this->headers->get('CONTENT_TYPE', ''));
  1151. }
  1152. /**
  1153. * Sets the default locale.
  1154. */
  1155. public function setDefaultLocale(string $locale)
  1156. {
  1157. $this->defaultLocale = $locale;
  1158. if (null === $this->locale) {
  1159. $this->setPhpDefaultLocale($locale);
  1160. }
  1161. }
  1162. /**
  1163. * Get the default locale.
  1164. */
  1165. public function getDefaultLocale(): string
  1166. {
  1167. return $this->defaultLocale;
  1168. }
  1169. /**
  1170. * Sets the locale.
  1171. */
  1172. public function setLocale(string $locale)
  1173. {
  1174. $this->setPhpDefaultLocale($this->locale = $locale);
  1175. }
  1176. /**
  1177. * Get the locale.
  1178. */
  1179. public function getLocale(): string
  1180. {
  1181. return null === $this->locale ? $this->defaultLocale : $this->locale;
  1182. }
  1183. /**
  1184. * Checks if the request method is of specified type.
  1185. *
  1186. * @param string $method Uppercase request method (GET, POST etc)
  1187. */
  1188. public function isMethod(string $method): bool
  1189. {
  1190. return $this->getMethod() === strtoupper($method);
  1191. }
  1192. /**
  1193. * Checks whether or not the method is safe.
  1194. *
  1195. * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
  1196. */
  1197. public function isMethodSafe(): bool
  1198. {
  1199. return \in_array($this->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE']);
  1200. }
  1201. /**
  1202. * Checks whether or not the method is idempotent.
  1203. */
  1204. public function isMethodIdempotent(): bool
  1205. {
  1206. return \in_array($this->getMethod(), ['HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE']);
  1207. }
  1208. /**
  1209. * Checks whether the method is cacheable or not.
  1210. *
  1211. * @see https://tools.ietf.org/html/rfc7231#section-4.2.3
  1212. */
  1213. public function isMethodCacheable(): bool
  1214. {
  1215. return \in_array($this->getMethod(), ['GET', 'HEAD']);
  1216. }
  1217. /**
  1218. * Returns the protocol version.
  1219. *
  1220. * If the application is behind a proxy, the protocol version used in the
  1221. * requests between the client and the proxy and between the proxy and the
  1222. * server might be different. This returns the former (from the "Via" header)
  1223. * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns
  1224. * the latter (from the "SERVER_PROTOCOL" server parameter).
  1225. */
  1226. public function getProtocolVersion(): ?string
  1227. {
  1228. if ($this->isFromTrustedProxy()) {
  1229. preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via') ?? '', $matches);
  1230. if ($matches) {
  1231. return 'HTTP/'.$matches[2];
  1232. }
  1233. }
  1234. return $this->server->get('SERVER_PROTOCOL');
  1235. }
  1236. /**
  1237. * Returns the request body content.
  1238. *
  1239. * @param bool $asResource If true, a resource will be returned
  1240. *
  1241. * @return string|resource
  1242. */
  1243. public function getContent(bool $asResource = false)
  1244. {
  1245. $currentContentIsResource = \is_resource($this->content);
  1246. if (true === $asResource) {
  1247. if ($currentContentIsResource) {
  1248. rewind($this->content);
  1249. return $this->content;
  1250. }
  1251. // Content passed in parameter (test)
  1252. if (\is_string($this->content)) {
  1253. $resource = fopen('php://temp', 'r+');
  1254. fwrite($resource, $this->content);
  1255. rewind($resource);
  1256. return $resource;
  1257. }
  1258. $this->content = false;
  1259. return fopen('php://input', 'r');
  1260. }
  1261. if ($currentContentIsResource) {
  1262. rewind($this->content);
  1263. return stream_get_contents($this->content);
  1264. }
  1265. if (null === $this->content || false === $this->content) {
  1266. $this->content = file_get_contents('php://input');
  1267. }
  1268. return $this->content;
  1269. }
  1270. /**
  1271. * Gets the request body decoded as array, typically from a JSON payload.
  1272. *
  1273. * @throws JsonException When the body cannot be decoded to an array
  1274. */
  1275. public function toArray(): array
  1276. {
  1277. if ('' === $content = $this->getContent()) {
  1278. throw new JsonException('Request body is empty.');
  1279. }
  1280. try {
  1281. $content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR);
  1282. } catch (\JsonException $e) {
  1283. throw new JsonException('Could not decode request body.', $e->getCode(), $e);
  1284. }
  1285. if (!\is_array($content)) {
  1286. throw new JsonException(sprintf('JSON content was expected to decode to an array, "%s" returned.', get_debug_type($content)));
  1287. }
  1288. return $content;
  1289. }
  1290. /**
  1291. * Gets the Etags.
  1292. */
  1293. public function getETags(): array
  1294. {
  1295. return preg_split('/\s*,\s*/', $this->headers->get('If-None-Match', ''), -1, \PREG_SPLIT_NO_EMPTY);
  1296. }
  1297. public function isNoCache(): bool
  1298. {
  1299. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  1300. }
  1301. /**
  1302. * Gets the preferred format for the response by inspecting, in the following order:
  1303. * * the request format set using setRequestFormat;
  1304. * * the values of the Accept HTTP header.
  1305. *
  1306. * Note that if you use this method, you should send the "Vary: Accept" header
  1307. * in the response to prevent any issues with intermediary HTTP caches.
  1308. */
  1309. public function getPreferredFormat(?string $default = 'html'): ?string
  1310. {
  1311. if (null !== $this->preferredFormat || null !== $this->preferredFormat = $this->getRequestFormat(null)) {
  1312. return $this->preferredFormat;
  1313. }
  1314. foreach ($this->getAcceptableContentTypes() as $mimeType) {
  1315. if ($this->preferredFormat = $this->getFormat($mimeType)) {
  1316. return $this->preferredFormat;
  1317. }
  1318. }
  1319. return $default;
  1320. }
  1321. /**
  1322. * Returns the preferred language.
  1323. *
  1324. * @param string[] $locales An array of ordered available locales
  1325. */
  1326. public function getPreferredLanguage(array $locales = null): ?string
  1327. {
  1328. $preferredLanguages = $this->getLanguages();
  1329. if (empty($locales)) {
  1330. return $preferredLanguages[0] ?? null;
  1331. }
  1332. if (!$preferredLanguages) {
  1333. return $locales[0];
  1334. }
  1335. $extendedPreferredLanguages = [];
  1336. foreach ($preferredLanguages as $language) {
  1337. $extendedPreferredLanguages[] = $language;
  1338. if (false !== $position = strpos($language, '_')) {
  1339. $superLanguage = substr($language, 0, $position);
  1340. if (!\in_array($superLanguage, $preferredLanguages)) {
  1341. $extendedPreferredLanguages[] = $superLanguage;
  1342. }
  1343. }
  1344. }
  1345. $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
  1346. return $preferredLanguages[0] ?? $locales[0];
  1347. }
  1348. /**
  1349. * Gets a list of languages acceptable by the client browser ordered in the user browser preferences.
  1350. */
  1351. public function getLanguages(): array
  1352. {
  1353. if (null !== $this->languages) {
  1354. return $this->languages;
  1355. }
  1356. $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
  1357. $this->languages = [];
  1358. foreach ($languages as $acceptHeaderItem) {
  1359. $lang = $acceptHeaderItem->getValue();
  1360. if (str_contains($lang, '-')) {
  1361. $codes = explode('-', $lang);
  1362. if ('i' === $codes[0]) {
  1363. // Language not listed in ISO 639 that are not variants
  1364. // of any listed language, which can be registered with the
  1365. // i-prefix, such as i-cherokee
  1366. if (\count($codes) > 1) {
  1367. $lang = $codes[1];
  1368. }
  1369. } else {
  1370. for ($i = 0, $max = \count($codes); $i < $max; ++$i) {
  1371. if (0 === $i) {
  1372. $lang = strtolower($codes[0]);
  1373. } else {
  1374. $lang .= '_'.strtoupper($codes[$i]);
  1375. }
  1376. }
  1377. }
  1378. }
  1379. $this->languages[] = $lang;
  1380. }
  1381. return $this->languages;
  1382. }
  1383. /**
  1384. * Gets a list of charsets acceptable by the client browser in preferable order.
  1385. */
  1386. public function getCharsets(): array
  1387. {
  1388. if (null !== $this->charsets) {
  1389. return $this->charsets;
  1390. }
  1391. return $this->charsets = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all()));
  1392. }
  1393. /**
  1394. * Gets a list of encodings acceptable by the client browser in preferable order.
  1395. */
  1396. public function getEncodings(): array
  1397. {
  1398. if (null !== $this->encodings) {
  1399. return $this->encodings;
  1400. }
  1401. return $this->encodings = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all()));
  1402. }
  1403. /**
  1404. * Gets a list of content types acceptable by the client browser in preferable order.
  1405. */
  1406. public function getAcceptableContentTypes(): array
  1407. {
  1408. if (null !== $this->acceptableContentTypes) {
  1409. return $this->acceptableContentTypes;
  1410. }
  1411. return $this->acceptableContentTypes = array_map('strval', array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all()));
  1412. }
  1413. /**
  1414. * Returns true if the request is an XMLHttpRequest.
  1415. *
  1416. * It works if your JavaScript library sets an X-Requested-With HTTP header.
  1417. * It is known to work with common JavaScript frameworks:
  1418. *
  1419. * @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
  1420. */
  1421. public function isXmlHttpRequest(): bool
  1422. {
  1423. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  1424. }
  1425. /**
  1426. * Checks whether the client browser prefers safe content or not according to RFC8674.
  1427. *
  1428. * @see https://tools.ietf.org/html/rfc8674
  1429. */
  1430. public function preferSafeContent(): bool
  1431. {
  1432. if (isset($this->isSafeContentPreferred)) {
  1433. return $this->isSafeContentPreferred;
  1434. }
  1435. if (!$this->isSecure()) {
  1436. // see https://tools.ietf.org/html/rfc8674#section-3
  1437. return $this->isSafeContentPreferred = false;
  1438. }
  1439. return $this->isSafeContentPreferred = AcceptHeader::fromString($this->headers->get('Prefer'))->has('safe');
  1440. }
  1441. /*
  1442. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  1443. *
  1444. * Code subject to the new BSD license (https://framework.zend.com/license).
  1445. *
  1446. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (https://www.zend.com/)
  1447. */
  1448. protected function prepareRequestUri()
  1449. {
  1450. $requestUri = '';
  1451. if ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) {
  1452. // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
  1453. $requestUri = $this->server->get('UNENCODED_URL');
  1454. $this->server->remove('UNENCODED_URL');
  1455. $this->server->remove('IIS_WasUrlRewritten');
  1456. } elseif ($this->server->has('REQUEST_URI')) {
  1457. $requestUri = $this->server->get('REQUEST_URI');
  1458. if ('' !== $requestUri && '/' === $requestUri[0]) {
  1459. // To only use path and query remove the fragment.
  1460. if (false !== $pos = strpos($requestUri, '#')) {
  1461. $requestUri = substr($requestUri, 0, $pos);
  1462. }
  1463. } else {
  1464. // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path,
  1465. // only use URL path.
  1466. $uriComponents = parse_url($requestUri);
  1467. if (isset($uriComponents['path'])) {
  1468. $requestUri = $uriComponents['path'];
  1469. }
  1470. if (isset($uriComponents['query'])) {
  1471. $requestUri .= '?'.$uriComponents['query'];
  1472. }
  1473. }
  1474. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  1475. // IIS 5.0, PHP as CGI
  1476. $requestUri = $this->server->get('ORIG_PATH_INFO');
  1477. if ('' != $this->server->get('QUERY_STRING')) {
  1478. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  1479. }
  1480. $this->server->remove('ORIG_PATH_INFO');
  1481. }
  1482. // normalize the request URI to ease creating sub-requests from this request
  1483. $this->server->set('REQUEST_URI', $requestUri);
  1484. return $requestUri;
  1485. }
  1486. /**
  1487. * Prepares the base URL.
  1488. */
  1489. protected function prepareBaseUrl(): string
  1490. {
  1491. $filename = basename($this->server->get('SCRIPT_FILENAME', ''));
  1492. if (basename($this->server->get('SCRIPT_NAME', '')) === $filename) {
  1493. $baseUrl = $this->server->get('SCRIPT_NAME');
  1494. } elseif (basename($this->server->get('PHP_SELF', '')) === $filename) {
  1495. $baseUrl = $this->server->get('PHP_SELF');
  1496. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME', '')) === $filename) {
  1497. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  1498. } else {
  1499. // Backtrack up the script_filename to find the portion matching
  1500. // php_self
  1501. $path = $this->server->get('PHP_SELF', '');
  1502. $file = $this->server->get('SCRIPT_FILENAME', '');
  1503. $segs = explode('/', trim($file, '/'));
  1504. $segs = array_reverse($segs);
  1505. $index = 0;
  1506. $last = \count($segs);
  1507. $baseUrl = '';
  1508. do {
  1509. $seg = $segs[$index];
  1510. $baseUrl = '/'.$seg.$baseUrl;
  1511. ++$index;
  1512. } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
  1513. }
  1514. // Does the baseUrl have anything in common with the request_uri?
  1515. $requestUri = $this->getRequestUri();
  1516. if ('' !== $requestUri && '/' !== $requestUri[0]) {
  1517. $requestUri = '/'.$requestUri;
  1518. }
  1519. if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
  1520. // full $baseUrl matches
  1521. return $prefix;
  1522. }
  1523. if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(\dirname($baseUrl), '/'.\DIRECTORY_SEPARATOR).'/')) {
  1524. // directory portion of $baseUrl matches
  1525. return rtrim($prefix, '/'.\DIRECTORY_SEPARATOR);
  1526. }
  1527. $truncatedRequestUri = $requestUri;
  1528. if (false !== $pos = strpos($requestUri, '?')) {
  1529. $truncatedRequestUri = substr($requestUri, 0, $pos);
  1530. }
  1531. $basename = basename($baseUrl ?? '');
  1532. if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
  1533. // no match whatsoever; set it blank
  1534. return '';
  1535. }
  1536. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  1537. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  1538. // from PATH_INFO or QUERY_STRING
  1539. if (\strlen($requestUri) >= \strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) {
  1540. $baseUrl = substr($requestUri, 0, $pos + \strlen($baseUrl));
  1541. }
  1542. return rtrim($baseUrl, '/'.\DIRECTORY_SEPARATOR);
  1543. }
  1544. /**
  1545. * Prepares the base path.
  1546. */
  1547. protected function prepareBasePath(): string
  1548. {
  1549. $baseUrl = $this->getBaseUrl();
  1550. if (empty($baseUrl)) {
  1551. return '';
  1552. }
  1553. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1554. if (basename($baseUrl) === $filename) {
  1555. $basePath = \dirname($baseUrl);
  1556. } else {
  1557. $basePath = $baseUrl;
  1558. }
  1559. if ('\\' === \DIRECTORY_SEPARATOR) {
  1560. $basePath = str_replace('\\', '/', $basePath);
  1561. }
  1562. return rtrim($basePath, '/');
  1563. }
  1564. /**
  1565. * Prepares the path info.
  1566. */
  1567. protected function preparePathInfo(): string
  1568. {
  1569. if (null === ($requestUri = $this->getRequestUri())) {
  1570. return '/';
  1571. }
  1572. // Remove the query string from REQUEST_URI
  1573. if (false !== $pos = strpos($requestUri, '?')) {
  1574. $requestUri = substr($requestUri, 0, $pos);
  1575. }
  1576. if ('' !== $requestUri && '/' !== $requestUri[0]) {
  1577. $requestUri = '/'.$requestUri;
  1578. }
  1579. if (null === ($baseUrl = $this->getBaseUrlReal())) {
  1580. return $requestUri;
  1581. }
  1582. $pathInfo = substr($requestUri, \strlen($baseUrl));
  1583. if (false === $pathInfo || '' === $pathInfo) {
  1584. // If substr() returns false then PATH_INFO is set to an empty string
  1585. return '/';
  1586. }
  1587. return $pathInfo;
  1588. }
  1589. /**
  1590. * Initializes HTTP request formats.
  1591. */
  1592. protected static function initializeFormats()
  1593. {
  1594. static::$formats = [
  1595. 'html' => ['text/html', 'application/xhtml+xml'],
  1596. 'txt' => ['text/plain'],
  1597. 'js' => ['application/javascript', 'application/x-javascript', 'text/javascript'],
  1598. 'css' => ['text/css'],
  1599. 'json' => ['application/json', 'application/x-json'],
  1600. 'jsonld' => ['application/ld+json'],
  1601. 'xml' => ['text/xml', 'application/xml', 'application/x-xml'],
  1602. 'rdf' => ['application/rdf+xml'],
  1603. 'atom' => ['application/atom+xml'],
  1604. 'rss' => ['application/rss+xml'],
  1605. 'form' => ['application/x-www-form-urlencoded', 'multipart/form-data'],
  1606. ];
  1607. }
  1608. private function setPhpDefaultLocale(string $locale): void
  1609. {
  1610. // if either the class Locale doesn't exist, or an exception is thrown when
  1611. // setting the default locale, the intl module is not installed, and
  1612. // the call can be ignored:
  1613. try {
  1614. if (class_exists(\Locale::class, false)) {
  1615. \Locale::setDefault($locale);
  1616. }
  1617. } catch (\Exception $e) {
  1618. }
  1619. }
  1620. /**
  1621. * Returns the prefix as encoded in the string when the string starts with
  1622. * the given prefix, null otherwise.
  1623. */
  1624. private function getUrlencodedPrefix(string $string, string $prefix): ?string
  1625. {
  1626. if (!str_starts_with(rawurldecode($string), $prefix)) {
  1627. return null;
  1628. }
  1629. $len = \strlen($prefix);
  1630. if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
  1631. return $match[0];
  1632. }
  1633. return null;
  1634. }
  1635. private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): static
  1636. {
  1637. if (self::$requestFactory) {
  1638. $request = (self::$requestFactory)($query, $request, $attributes, $cookies, $files, $server, $content);
  1639. if (!$request instanceof self) {
  1640. throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
  1641. }
  1642. return $request;
  1643. }
  1644. return new static($query, $request, $attributes, $cookies, $files, $server, $content);
  1645. }
  1646. /**
  1647. * Indicates whether this request originated from a trusted proxy.
  1648. *
  1649. * This can be useful to determine whether or not to trust the
  1650. * contents of a proxy-specific header.
  1651. */
  1652. public function isFromTrustedProxy(): bool
  1653. {
  1654. return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR', ''), self::$trustedProxies);
  1655. }
  1656. private function getTrustedValues(int $type, string $ip = null): array
  1657. {
  1658. $clientValues = [];
  1659. $forwardedValues = [];
  1660. if ((self::$trustedHeaderSet & $type) && $this->headers->has(self::TRUSTED_HEADERS[$type])) {
  1661. foreach (explode(',', $this->headers->get(self::TRUSTED_HEADERS[$type])) as $v) {
  1662. $clientValues[] = (self::HEADER_X_FORWARDED_PORT === $type ? '0.0.0.0:' : '').trim($v);
  1663. }
  1664. }
  1665. if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && (isset(self::FORWARDED_PARAMS[$type])) && $this->headers->has(self::TRUSTED_HEADERS[self::HEADER_FORWARDED])) {
  1666. $forwarded = $this->headers->get(self::TRUSTED_HEADERS[self::HEADER_FORWARDED]);
  1667. $parts = HeaderUtils::split($forwarded, ',;=');
  1668. $forwardedValues = [];
  1669. $param = self::FORWARDED_PARAMS[$type];
  1670. foreach ($parts as $subParts) {
  1671. if (null === $v = HeaderUtils::combine($subParts)[$param] ?? null) {
  1672. continue;
  1673. }
  1674. if (self::HEADER_X_FORWARDED_PORT === $type) {
  1675. if (str_ends_with($v, ']') || false === $v = strrchr($v, ':')) {
  1676. $v = $this->isSecure() ? ':443' : ':80';
  1677. }
  1678. $v = '0.0.0.0'.$v;
  1679. }
  1680. $forwardedValues[] = $v;
  1681. }
  1682. }
  1683. if (null !== $ip) {
  1684. $clientValues = $this->normalizeAndFilterClientIps($clientValues, $ip);
  1685. $forwardedValues = $this->normalizeAndFilterClientIps($forwardedValues, $ip);
  1686. }
  1687. if ($forwardedValues === $clientValues || !$clientValues) {
  1688. return $forwardedValues;
  1689. }
  1690. if (!$forwardedValues) {
  1691. return $clientValues;
  1692. }
  1693. if (!$this->isForwardedValid) {
  1694. return null !== $ip ? ['0.0.0.0', $ip] : [];
  1695. }
  1696. $this->isForwardedValid = false;
  1697. throw new ConflictingHeadersException(sprintf('The request has both a trusted "%s" header and a trusted "%s" header, conflicting with each other. You should either configure your proxy to remove one of them, or configure your project to distrust the offending one.', self::TRUSTED_HEADERS[self::HEADER_FORWARDED], self::TRUSTED_HEADERS[$type]));
  1698. }
  1699. private function normalizeAndFilterClientIps(array $clientIps, string $ip): array
  1700. {
  1701. if (!$clientIps) {
  1702. return [];
  1703. }
  1704. $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
  1705. $firstTrustedIp = null;
  1706. foreach ($clientIps as $key => $clientIp) {
  1707. if (strpos($clientIp, '.')) {
  1708. // Strip :port from IPv4 addresses. This is allowed in Forwarded
  1709. // and may occur in X-Forwarded-For.
  1710. $i = strpos($clientIp, ':');
  1711. if ($i) {
  1712. $clientIps[$key] = $clientIp = substr($clientIp, 0, $i);
  1713. }
  1714. } elseif (str_starts_with($clientIp, '[')) {
  1715. // Strip brackets and :port from IPv6 addresses.
  1716. $i = strpos($clientIp, ']', 1);
  1717. $clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1);
  1718. }
  1719. if (!filter_var($clientIp, \FILTER_VALIDATE_IP)) {
  1720. unset($clientIps[$key]);
  1721. continue;
  1722. }
  1723. if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
  1724. unset($clientIps[$key]);
  1725. // Fallback to this when the client IP falls into the range of trusted proxies
  1726. if (null === $firstTrustedIp) {
  1727. $firstTrustedIp = $clientIp;
  1728. }
  1729. }
  1730. }
  1731. // Now the IP chain contains only untrusted proxies and the client IP
  1732. return $clientIps ? array_reverse($clientIps) : [$firstTrustedIp];
  1733. }
  1734. }