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