Request.php 67 KB

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