vendor/symfony/http-foundation/Request.php line 43

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