4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
14 use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;
15 use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
16 use Symfony\Component\HttpFoundation\Session\SessionInterface;
19 * Request represents an HTTP request.
21 * The methods dealing with URL accept / return a raw path (% encoded):
29 * @author Fabien Potencier <fabien@symfony.com>
33 const HEADER_FORWARDED = 0b00001; // When using RFC 7239
34 const HEADER_X_FORWARDED_FOR = 0b00010;
35 const HEADER_X_FORWARDED_HOST = 0b00100;
36 const HEADER_X_FORWARDED_PROTO = 0b01000;
37 const HEADER_X_FORWARDED_PORT = 0b10000;
38 const HEADER_X_FORWARDED_ALL = 0b11110; // All "X-Forwarded-*" headers
39 const HEADER_X_FORWARDED_AWS_ELB = 0b11010; // AWS ELB doesn't send X-Forwarded-Host
41 /** @deprecated since version 3.3, to be removed in 4.0 */
42 const HEADER_CLIENT_IP = self::HEADER_X_FORWARDED_FOR;
43 /** @deprecated since version 3.3, to be removed in 4.0 */
44 const HEADER_CLIENT_HOST = self::HEADER_X_FORWARDED_HOST;
45 /** @deprecated since version 3.3, to be removed in 4.0 */
46 const HEADER_CLIENT_PROTO = self::HEADER_X_FORWARDED_PROTO;
47 /** @deprecated since version 3.3, to be removed in 4.0 */
48 const HEADER_CLIENT_PORT = self::HEADER_X_FORWARDED_PORT;
50 const METHOD_HEAD = 'HEAD';
51 const METHOD_GET = 'GET';
52 const METHOD_POST = 'POST';
53 const METHOD_PUT = 'PUT';
54 const METHOD_PATCH = 'PATCH';
55 const METHOD_DELETE = 'DELETE';
56 const METHOD_PURGE = 'PURGE';
57 const METHOD_OPTIONS = 'OPTIONS';
58 const METHOD_TRACE = 'TRACE';
59 const METHOD_CONNECT = 'CONNECT';
64 protected static $trustedProxies = array();
69 protected static $trustedHostPatterns = array();
74 protected static $trustedHosts = array();
77 * Names for headers that can be trusted when
78 * using trusted proxies.
80 * The FORWARDED header is the standard as of rfc7239.
82 * The other headers are non-standard, but widely used
83 * by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
85 * @deprecated since version 3.3, to be removed in 4.0
87 protected static $trustedHeaders = array(
88 self::HEADER_FORWARDED => 'FORWARDED',
89 self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',
90 self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST',
91 self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
92 self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT',
95 protected static $httpMethodParameterOverride = false;
100 * @var \Symfony\Component\HttpFoundation\ParameterBag
105 * Request body parameters ($_POST).
107 * @var \Symfony\Component\HttpFoundation\ParameterBag
112 * Query string parameters ($_GET).
114 * @var \Symfony\Component\HttpFoundation\ParameterBag
119 * Server and execution environment parameters ($_SERVER).
121 * @var \Symfony\Component\HttpFoundation\ServerBag
126 * Uploaded files ($_FILES).
128 * @var \Symfony\Component\HttpFoundation\FileBag
133 * Cookies ($_COOKIE).
135 * @var \Symfony\Component\HttpFoundation\ParameterBag
140 * Headers (taken from the $_SERVER).
142 * @var \Symfony\Component\HttpFoundation\HeaderBag
147 * @var string|resource|false|null
154 protected $languages;
164 protected $encodings;
169 protected $acceptableContentTypes;
179 protected $requestUri;
202 * @var \Symfony\Component\HttpFoundation\Session\SessionInterface
214 protected $defaultLocale = 'en';
219 protected static $formats;
221 protected static $requestFactory;
223 private $isHostValid = true;
224 private $isForwardedValid = true;
226 private static $trustedHeaderSet = -1;
228 /** @deprecated since version 3.3, to be removed in 4.0 */
229 private static $trustedHeaderNames = array(
230 self::HEADER_FORWARDED => 'FORWARDED',
231 self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',
232 self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST',
233 self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
234 self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT',
237 private static $forwardedParams = array(
238 self::HEADER_X_FORWARDED_FOR => 'for',
239 self::HEADER_X_FORWARDED_HOST => 'host',
240 self::HEADER_X_FORWARDED_PROTO => 'proto',
241 self::HEADER_X_FORWARDED_PORT => 'host',
245 * @param array $query The GET parameters
246 * @param array $request The POST parameters
247 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
248 * @param array $cookies The COOKIE parameters
249 * @param array $files The FILES parameters
250 * @param array $server The SERVER parameters
251 * @param string|resource|null $content The raw body data
253 public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
255 $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
259 * Sets the parameters for this request.
261 * This method also re-initializes all properties.
263 * @param array $query The GET parameters
264 * @param array $request The POST parameters
265 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
266 * @param array $cookies The COOKIE parameters
267 * @param array $files The FILES parameters
268 * @param array $server The SERVER parameters
269 * @param string|resource|null $content The raw body data
271 public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
273 $this->request = new ParameterBag($request);
274 $this->query = new ParameterBag($query);
275 $this->attributes = new ParameterBag($attributes);
276 $this->cookies = new ParameterBag($cookies);
277 $this->files = new FileBag($files);
278 $this->server = new ServerBag($server);
279 $this->headers = new HeaderBag($this->server->getHeaders());
281 $this->content = $content;
282 $this->languages = null;
283 $this->charsets = null;
284 $this->encodings = null;
285 $this->acceptableContentTypes = null;
286 $this->pathInfo = null;
287 $this->requestUri = null;
288 $this->baseUrl = null;
289 $this->basePath = null;
290 $this->method = null;
291 $this->format = null;
295 * Creates a new request with values from PHP's super globals.
299 public static function createFromGlobals()
301 // With the php's bug #66606, the php's built-in web server
302 // stores the Content-Type and Content-Length header values in
303 // HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields.
305 if ('cli-server' === PHP_SAPI) {
306 if (array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) {
307 $server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH'];
309 if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) {
310 $server['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE'];
314 $request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $server);
316 if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
317 && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
319 parse_str($request->getContent(), $data);
320 $request->request = new ParameterBag($data);
327 * Creates a Request based on a given URI and configuration.
329 * The information contained in the URI always take precedence
330 * over the other information (server and parameters).
332 * @param string $uri The URI
333 * @param string $method The HTTP method
334 * @param array $parameters The query (GET) or request (POST) parameters
335 * @param array $cookies The request cookies ($_COOKIE)
336 * @param array $files The request files ($_FILES)
337 * @param array $server The server parameters ($_SERVER)
338 * @param string|resource|null $content The raw body data
342 public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
344 $server = array_replace(array(
345 'SERVER_NAME' => 'localhost',
347 'HTTP_HOST' => 'localhost',
348 'HTTP_USER_AGENT' => 'Symfony/3.X',
349 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
350 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
351 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
352 'REMOTE_ADDR' => '127.0.0.1',
354 'SCRIPT_FILENAME' => '',
355 'SERVER_PROTOCOL' => 'HTTP/1.1',
356 'REQUEST_TIME' => time(),
359 $server['PATH_INFO'] = '';
360 $server['REQUEST_METHOD'] = strtoupper($method);
362 $components = parse_url($uri);
363 if (isset($components['host'])) {
364 $server['SERVER_NAME'] = $components['host'];
365 $server['HTTP_HOST'] = $components['host'];
368 if (isset($components['scheme'])) {
369 if ('https' === $components['scheme']) {
370 $server['HTTPS'] = 'on';
371 $server['SERVER_PORT'] = 443;
373 unset($server['HTTPS']);
374 $server['SERVER_PORT'] = 80;
378 if (isset($components['port'])) {
379 $server['SERVER_PORT'] = $components['port'];
380 $server['HTTP_HOST'] = $server['HTTP_HOST'].':'.$components['port'];
383 if (isset($components['user'])) {
384 $server['PHP_AUTH_USER'] = $components['user'];
387 if (isset($components['pass'])) {
388 $server['PHP_AUTH_PW'] = $components['pass'];
391 if (!isset($components['path'])) {
392 $components['path'] = '/';
395 switch (strtoupper($method)) {
399 if (!isset($server['CONTENT_TYPE'])) {
400 $server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
404 $request = $parameters;
409 $query = $parameters;
414 if (isset($components['query'])) {
415 parse_str(html_entity_decode($components['query']), $qs);
418 $query = array_replace($qs, $query);
419 $queryString = http_build_query($query, '', '&');
422 $queryString = $components['query'];
425 $queryString = http_build_query($query, '', '&');
428 $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : '');
429 $server['QUERY_STRING'] = $queryString;
431 return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content);
435 * Sets a callable able to create a Request instance.
437 * This is mainly useful when you need to override the Request class
438 * to keep BC with an existing system. It should not be used for any
441 * @param callable|null $callable A PHP callable
443 public static function setFactory($callable)
445 self::$requestFactory = $callable;
449 * Clones a request and overrides some of its parameters.
451 * @param array $query The GET parameters
452 * @param array $request The POST parameters
453 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
454 * @param array $cookies The COOKIE parameters
455 * @param array $files The FILES parameters
456 * @param array $server The SERVER parameters
460 public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
463 if (null !== $query) {
464 $dup->query = new ParameterBag($query);
466 if (null !== $request) {
467 $dup->request = new ParameterBag($request);
469 if (null !== $attributes) {
470 $dup->attributes = new ParameterBag($attributes);
472 if (null !== $cookies) {
473 $dup->cookies = new ParameterBag($cookies);
475 if (null !== $files) {
476 $dup->files = new FileBag($files);
478 if (null !== $server) {
479 $dup->server = new ServerBag($server);
480 $dup->headers = new HeaderBag($dup->server->getHeaders());
482 $dup->languages = null;
483 $dup->charsets = null;
484 $dup->encodings = null;
485 $dup->acceptableContentTypes = null;
486 $dup->pathInfo = null;
487 $dup->requestUri = null;
488 $dup->baseUrl = null;
489 $dup->basePath = null;
493 if (!$dup->get('_format') && $this->get('_format')) {
494 $dup->attributes->set('_format', $this->get('_format'));
497 if (!$dup->getRequestFormat(null)) {
498 $dup->setRequestFormat($this->getRequestFormat(null));
505 * Clones the current request.
507 * Note that the session is not cloned as duplicated requests
508 * are most of the time sub-requests of the main one.
510 public function __clone()
512 $this->query = clone $this->query;
513 $this->request = clone $this->request;
514 $this->attributes = clone $this->attributes;
515 $this->cookies = clone $this->cookies;
516 $this->files = clone $this->files;
517 $this->server = clone $this->server;
518 $this->headers = clone $this->headers;
522 * Returns the request as a string.
524 * @return string The request
526 public function __toString()
529 $content = $this->getContent();
530 } catch (\LogicException $e) {
531 return trigger_error($e, E_USER_ERROR);
537 foreach ($this->cookies as $k => $v) {
538 $cookies[] = $k.'='.$v;
541 if (!empty($cookies)) {
542 $cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
546 sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
548 $cookieHeader."\r\n".
553 * Overrides the PHP global variables according to this request instance.
555 * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE.
556 * $_FILES is never overridden, see rfc1867
558 public function overrideGlobals()
560 $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '', '&')));
562 $_GET = $this->query->all();
563 $_POST = $this->request->all();
564 $_SERVER = $this->server->all();
565 $_COOKIE = $this->cookies->all();
567 foreach ($this->headers->all() as $key => $value) {
568 $key = strtoupper(str_replace('-', '_', $key));
569 if (in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
570 $_SERVER[$key] = implode(', ', $value);
572 $_SERVER['HTTP_'.$key] = implode(', ', $value);
576 $request = array('g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE);
578 $requestOrder = ini_get('request_order') ?: ini_get('variables_order');
579 $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp';
582 foreach (str_split($requestOrder) as $order) {
583 $_REQUEST = array_merge($_REQUEST, $request[$order]);
588 * Sets a list of trusted proxies.
590 * You should only list the reverse proxies that you manage directly.
592 * @param array $proxies A list of trusted proxies
593 * @param int $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies
595 * @throws \InvalidArgumentException When $trustedHeaderSet is invalid
597 public static function setTrustedProxies(array $proxies/*, int $trustedHeaderSet*/)
599 self::$trustedProxies = $proxies;
601 if (2 > func_num_args()) {
602 @trigger_error(sprintf('The %s() method expects a bit field of Request::HEADER_* as second argument since Symfony 3.3. Defining it will be required in 4.0. ', __METHOD__), E_USER_DEPRECATED);
606 $trustedHeaderSet = (int) func_get_arg(1);
608 foreach (self::$trustedHeaderNames as $header => $name) {
609 self::$trustedHeaders[$header] = $header & $trustedHeaderSet ? $name : null;
611 self::$trustedHeaderSet = $trustedHeaderSet;
615 * Gets the list of trusted proxies.
617 * @return array An array of trusted proxies
619 public static function getTrustedProxies()
621 return self::$trustedProxies;
625 * Gets the set of trusted headers from trusted proxies.
627 * @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies
629 public static function getTrustedHeaderSet()
631 return self::$trustedHeaderSet;
635 * Sets a list of trusted host patterns.
637 * You should only list the hosts you manage using regexs.
639 * @param array $hostPatterns A list of trusted host patterns
641 public static function setTrustedHosts(array $hostPatterns)
643 self::$trustedHostPatterns = array_map(function ($hostPattern) {
644 return sprintf('#%s#i', $hostPattern);
646 // we need to reset trusted hosts on trusted host patterns change
647 self::$trustedHosts = array();
651 * Gets the list of trusted host patterns.
653 * @return array An array of trusted host patterns
655 public static function getTrustedHosts()
657 return self::$trustedHostPatterns;
661 * Sets the name for trusted headers.
663 * The following header keys are supported:
665 * * Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp())
666 * * Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getHost())
667 * * Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getPort())
668 * * Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure())
669 * * Request::HEADER_FORWARDED: defaults to Forwarded (see RFC 7239)
671 * Setting an empty value allows to disable the trusted header for the given key.
673 * @param string $key The header key
674 * @param string $value The header name
676 * @throws \InvalidArgumentException
678 * @deprecated since version 3.3, to be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.
680 public static function setTrustedHeaderName($key, $value)
682 @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead.', __METHOD__), E_USER_DEPRECATED);
684 if ('forwarded' === $key) {
685 $key = self::HEADER_FORWARDED;
686 } elseif ('client_ip' === $key) {
687 $key = self::HEADER_CLIENT_IP;
688 } elseif ('client_host' === $key) {
689 $key = self::HEADER_CLIENT_HOST;
690 } elseif ('client_proto' === $key) {
691 $key = self::HEADER_CLIENT_PROTO;
692 } elseif ('client_port' === $key) {
693 $key = self::HEADER_CLIENT_PORT;
694 } elseif (!array_key_exists($key, self::$trustedHeaders)) {
695 throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key));
698 self::$trustedHeaders[$key] = $value;
700 if (null !== $value) {
701 self::$trustedHeaderNames[$key] = $value;
702 self::$trustedHeaderSet |= $key;
704 self::$trustedHeaderSet &= ~$key;
709 * Gets the trusted proxy header name.
711 * @param string $key The header key
713 * @return string The header name
715 * @throws \InvalidArgumentException
717 * @deprecated since version 3.3, to be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead.
719 public static function getTrustedHeaderName($key)
721 if (2 > func_num_args() || func_get_arg(1)) {
722 @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.3 and will be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead.', __METHOD__), E_USER_DEPRECATED);
725 if (!array_key_exists($key, self::$trustedHeaders)) {
726 throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key));
729 return self::$trustedHeaders[$key];
733 * Normalizes a query string.
735 * It builds a normalized query string, where keys/value pairs are alphabetized,
736 * have consistent escaping and unneeded delimiters are removed.
738 * @param string $qs Query string
740 * @return string A normalized query string for the Request
742 public static function normalizeQueryString($qs)
751 foreach (explode('&', $qs) as $param) {
752 if ('' === $param || '=' === $param[0]) {
753 // Ignore useless delimiters, e.g. "x=y&".
754 // Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
755 // PHP also does not include them when building _GET.
759 $keyValuePair = explode('=', $param, 2);
761 // GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
762 // PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. This is why we use urldecode and then normalize to
763 // RFC 3986 with rawurlencode.
764 $parts[] = isset($keyValuePair[1]) ?
765 rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
766 rawurlencode(urldecode($keyValuePair[0]));
767 $order[] = urldecode($keyValuePair[0]);
770 array_multisort($order, SORT_ASC, $parts);
772 return implode('&', $parts);
776 * Enables support for the _method request parameter to determine the intended HTTP method.
778 * Be warned that enabling this feature might lead to CSRF issues in your code.
779 * Check that you are using CSRF tokens when required.
780 * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered
781 * and used to send a "PUT" or "DELETE" request via the _method request parameter.
782 * If these methods are not protected against CSRF, this presents a possible vulnerability.
784 * The HTTP method can only be overridden when the real HTTP method is POST.
786 public static function enableHttpMethodParameterOverride()
788 self::$httpMethodParameterOverride = true;
792 * Checks whether support for the _method request parameter is enabled.
794 * @return bool True when the _method request parameter is enabled, false otherwise
796 public static function getHttpMethodParameterOverride()
798 return self::$httpMethodParameterOverride;
802 * Gets a "parameter" value from any bag.
804 * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the
805 * flexibility in controllers, it is better to explicitly get request parameters from the appropriate
806 * public property instead (attributes, query, request).
808 * Order of precedence: PATH (routing placeholders or custom attributes), GET, BODY
810 * @param string $key The key
811 * @param mixed $default The default value if the parameter key does not exist
815 public function get($key, $default = null)
817 if ($this !== $result = $this->attributes->get($key, $this)) {
821 if ($this !== $result = $this->query->get($key, $this)) {
825 if ($this !== $result = $this->request->get($key, $this)) {
835 * @return SessionInterface|null The session
837 public function getSession()
839 return $this->session;
843 * Whether the request contains a Session which was started in one of the
848 public function hasPreviousSession()
850 // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
851 return $this->hasSession() && $this->cookies->has($this->session->getName());
855 * Whether the request contains a Session object.
857 * This method does not give any information about the state of the session object,
858 * like whether the session is started or not. It is just a way to check if this Request
859 * is associated with a Session instance.
861 * @return bool true when the Request contains a Session object, false otherwise
863 public function hasSession()
865 return null !== $this->session;
871 * @param SessionInterface $session The Session
873 public function setSession(SessionInterface $session)
875 $this->session = $session;
879 * Returns the client IP addresses.
881 * In the returned array the most trusted IP address is first, and the
882 * least trusted one last. The "real" client IP address is the last one,
883 * but this is also the least trusted one. Trusted proxies are stripped.
885 * Use this method carefully; you should use getClientIp() instead.
887 * @return array The client IP addresses
891 public function getClientIps()
893 $ip = $this->server->get('REMOTE_ADDR');
895 if (!$this->isFromTrustedProxy()) {
899 return $this->getTrustedValues(self::HEADER_CLIENT_IP, $ip) ?: array($ip);
903 * Returns the client IP address.
905 * This method can read the client IP address from the "X-Forwarded-For" header
906 * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
907 * header value is a comma+space separated list of IP addresses, the left-most
908 * being the original client, and each successive proxy that passed the request
909 * adding the IP address where it received the request from.
911 * If your reverse proxy uses a different header name than "X-Forwarded-For",
912 * ("Client-Ip" for instance), configure it via the $trustedHeaderSet
913 * argument of the Request::setTrustedProxies() method instead.
915 * @return string|null The client IP address
917 * @see getClientIps()
918 * @see http://en.wikipedia.org/wiki/X-Forwarded-For
920 public function getClientIp()
922 $ipAddresses = $this->getClientIps();
924 return $ipAddresses[0];
928 * Returns current script name.
932 public function getScriptName()
934 return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
938 * Returns the path being requested relative to the executed script.
940 * The path info always starts with a /.
942 * Suppose this request is instantiated from /mysite on localhost:
944 * * http://localhost/mysite returns an empty string
945 * * http://localhost/mysite/about returns '/about'
946 * * http://localhost/mysite/enco%20ded returns '/enco%20ded'
947 * * http://localhost/mysite/about?var=1 returns '/about'
949 * @return string The raw path (i.e. not urldecoded)
951 public function getPathInfo()
953 if (null === $this->pathInfo) {
954 $this->pathInfo = $this->preparePathInfo();
957 return $this->pathInfo;
961 * Returns the root path from which this request is executed.
963 * Suppose that an index.php file instantiates this request object:
965 * * http://localhost/index.php returns an empty string
966 * * http://localhost/index.php/page returns an empty string
967 * * http://localhost/web/index.php returns '/web'
968 * * http://localhost/we%20b/index.php returns '/we%20b'
970 * @return string The raw path (i.e. not urldecoded)
972 public function getBasePath()
974 if (null === $this->basePath) {
975 $this->basePath = $this->prepareBasePath();
978 return $this->basePath;
982 * Returns the root URL from which this request is executed.
984 * The base URL never ends with a /.
986 * This is similar to getBasePath(), except that it also includes the
987 * script filename (e.g. index.php) if one exists.
989 * @return string The raw URL (i.e. not urldecoded)
991 public function getBaseUrl()
993 if (null === $this->baseUrl) {
994 $this->baseUrl = $this->prepareBaseUrl();
997 return $this->baseUrl;
1001 * Gets the request's scheme.
1005 public function getScheme()
1007 return $this->isSecure() ? 'https' : 'http';
1011 * Returns the port on which the request is made.
1013 * This method can read the client port from the "X-Forwarded-Port" header
1014 * when trusted proxies were set via "setTrustedProxies()".
1016 * The "X-Forwarded-Port" header must contain the client port.
1018 * If your reverse proxy uses a different header name than "X-Forwarded-Port",
1019 * configure it via via the $trustedHeaderSet argument of the
1020 * Request::setTrustedProxies() method instead.
1022 * @return int|string can be a string if fetched from the server bag
1024 public function getPort()
1026 if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_PORT)) {
1028 } elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_HOST)) {
1030 } elseif (!$host = $this->headers->get('HOST')) {
1031 return $this->server->get('SERVER_PORT');
1034 if ('[' === $host[0]) {
1035 $pos = strpos($host, ':', strrpos($host, ']'));
1037 $pos = strrpos($host, ':');
1040 if (false !== $pos) {
1041 return (int) substr($host, $pos + 1);
1044 return 'https' === $this->getScheme() ? 443 : 80;
1050 * @return string|null
1052 public function getUser()
1054 return $this->headers->get('PHP_AUTH_USER');
1058 * Returns the password.
1060 * @return string|null
1062 public function getPassword()
1064 return $this->headers->get('PHP_AUTH_PW');
1068 * Gets the user info.
1070 * @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server
1072 public function getUserInfo()
1074 $userinfo = $this->getUser();
1076 $pass = $this->getPassword();
1078 $userinfo .= ":$pass";
1085 * Returns the HTTP host being requested.
1087 * The port name will be appended to the host if it's non-standard.
1091 public function getHttpHost()
1093 $scheme = $this->getScheme();
1094 $port = $this->getPort();
1096 if (('http' == $scheme && 80 == $port) || ('https' == $scheme && 443 == $port)) {
1097 return $this->getHost();
1100 return $this->getHost().':'.$port;
1104 * Returns the requested URI (path and query string).
1106 * @return string The raw URI (i.e. not URI decoded)
1108 public function getRequestUri()
1110 if (null === $this->requestUri) {
1111 $this->requestUri = $this->prepareRequestUri();
1114 return $this->requestUri;
1118 * Gets the scheme and HTTP host.
1120 * If the URL was called with basic authentication, the user
1121 * and the password are not added to the generated string.
1123 * @return string The scheme and HTTP host
1125 public function getSchemeAndHttpHost()
1127 return $this->getScheme().'://'.$this->getHttpHost();
1131 * Generates a normalized URI (URL) for the Request.
1133 * @return string A normalized URI (URL) for the Request
1135 * @see getQueryString()
1137 public function getUri()
1139 if (null !== $qs = $this->getQueryString()) {
1143 return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
1147 * Generates a normalized URI for the given path.
1149 * @param string $path A path to use instead of the current one
1151 * @return string The normalized URI for the path
1153 public function getUriForPath($path)
1155 return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
1159 * Returns the path as relative reference from the current Request path.
1161 * Only the URIs path component (no schema, host etc.) is relevant and must be given.
1162 * Both paths must be absolute and not contain relative parts.
1163 * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
1164 * Furthermore, they can be used to reduce the link size in documents.
1166 * Example target paths, given a base path of "/a/b/c/d":
1167 * - "/a/b/c/d" -> ""
1168 * - "/a/b/c/" -> "./"
1169 * - "/a/b/" -> "../"
1170 * - "/a/b/c/other" -> "other"
1171 * - "/a/x/y" -> "../../x/y"
1173 * @param string $path The target path
1175 * @return string The relative target path
1177 public function getRelativeUriForPath($path)
1179 // be sure that we are dealing with an absolute path
1180 if (!isset($path[0]) || '/' !== $path[0]) {
1184 if ($path === $basePath = $this->getPathInfo()) {
1188 $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
1189 $targetDirs = explode('/', isset($path[0]) && '/' === $path[0] ? substr($path, 1) : $path);
1190 array_pop($sourceDirs);
1191 $targetFile = array_pop($targetDirs);
1193 foreach ($sourceDirs as $i => $dir) {
1194 if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
1195 unset($sourceDirs[$i], $targetDirs[$i]);
1201 $targetDirs[] = $targetFile;
1202 $path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
1204 // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
1205 // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
1206 // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
1207 // (see http://tools.ietf.org/html/rfc3986#section-4.2).
1208 return !isset($path[0]) || '/' === $path[0]
1209 || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
1210 ? "./$path" : $path;
1214 * Generates the normalized query string for the Request.
1216 * It builds a normalized query string, where keys/value pairs are alphabetized
1217 * and have consistent escaping.
1219 * @return string|null A normalized query string for the Request
1221 public function getQueryString()
1223 $qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
1225 return '' === $qs ? null : $qs;
1229 * Checks whether the request is secure or not.
1231 * This method can read the client protocol from the "X-Forwarded-Proto" header
1232 * when trusted proxies were set via "setTrustedProxies()".
1234 * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
1236 * If your reverse proxy uses a different header name than "X-Forwarded-Proto"
1237 * ("SSL_HTTPS" for instance), configure it via the $trustedHeaderSet
1238 * argument of the Request::setTrustedProxies() method instead.
1242 public function isSecure()
1244 if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_CLIENT_PROTO)) {
1245 return in_array(strtolower($proto[0]), array('https', 'on', 'ssl', '1'), true);
1248 $https = $this->server->get('HTTPS');
1250 return !empty($https) && 'off' !== strtolower($https);
1254 * Returns the host name.
1256 * This method can read the client host name from the "X-Forwarded-Host" header
1257 * when trusted proxies were set via "setTrustedProxies()".
1259 * The "X-Forwarded-Host" header must contain the client host name.
1261 * If your reverse proxy uses a different header name than "X-Forwarded-Host",
1262 * configure it via the $trustedHeaderSet argument of the
1263 * Request::setTrustedProxies() method instead.
1267 * @throws SuspiciousOperationException when the host name is invalid or not trusted
1269 public function getHost()
1271 if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_HOST)) {
1273 } elseif (!$host = $this->headers->get('HOST')) {
1274 if (!$host = $this->server->get('SERVER_NAME')) {
1275 $host = $this->server->get('SERVER_ADDR', '');
1279 // trim and remove port number from host
1280 // host is lowercase as per RFC 952/2181
1281 $host = strtolower(preg_replace('/:\d+$/', '', trim($host)));
1283 // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
1284 // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
1285 // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
1286 if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
1287 if (!$this->isHostValid) {
1290 $this->isHostValid = false;
1292 throw new SuspiciousOperationException(sprintf('Invalid Host "%s".', $host));
1295 if (count(self::$trustedHostPatterns) > 0) {
1296 // to avoid host header injection attacks, you should provide a list of trusted host patterns
1298 if (in_array($host, self::$trustedHosts)) {
1302 foreach (self::$trustedHostPatterns as $pattern) {
1303 if (preg_match($pattern, $host)) {
1304 self::$trustedHosts[] = $host;
1310 if (!$this->isHostValid) {
1313 $this->isHostValid = false;
1315 throw new SuspiciousOperationException(sprintf('Untrusted Host "%s".', $host));
1322 * Sets the request method.
1324 * @param string $method
1326 public function setMethod($method)
1328 $this->method = null;
1329 $this->server->set('REQUEST_METHOD', $method);
1333 * Gets the request "intended" method.
1335 * If the X-HTTP-Method-Override header is set, and if the method is a POST,
1336 * then it is used to determine the "real" intended HTTP method.
1338 * The _method request parameter can also be used to determine the HTTP method,
1339 * but only if enableHttpMethodParameterOverride() has been called.
1341 * The method is always an uppercased string.
1343 * @return string The request method
1345 * @see getRealMethod()
1347 public function getMethod()
1349 if (null === $this->method) {
1350 $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
1352 if ('POST' === $this->method) {
1353 if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
1354 $this->method = strtoupper($method);
1355 } elseif (self::$httpMethodParameterOverride) {
1356 $this->method = strtoupper($this->request->get('_method', $this->query->get('_method', 'POST')));
1361 return $this->method;
1365 * Gets the "real" request method.
1367 * @return string The request method
1371 public function getRealMethod()
1373 return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
1377 * Gets the mime type associated with the format.
1379 * @param string $format The format
1381 * @return string The associated mime type (null if not found)
1383 public function getMimeType($format)
1385 if (null === static::$formats) {
1386 static::initializeFormats();
1389 return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
1393 * Gets the mime types associated with the format.
1395 * @param string $format The format
1397 * @return array The associated mime types
1399 public static function getMimeTypes($format)
1401 if (null === static::$formats) {
1402 static::initializeFormats();
1405 return isset(static::$formats[$format]) ? static::$formats[$format] : array();
1409 * Gets the format associated with the mime type.
1411 * @param string $mimeType The associated mime type
1413 * @return string|null The format (null if not found)
1415 public function getFormat($mimeType)
1417 $canonicalMimeType = null;
1418 if (false !== $pos = strpos($mimeType, ';')) {
1419 $canonicalMimeType = substr($mimeType, 0, $pos);
1422 if (null === static::$formats) {
1423 static::initializeFormats();
1426 foreach (static::$formats as $format => $mimeTypes) {
1427 if (in_array($mimeType, (array) $mimeTypes)) {
1430 if (null !== $canonicalMimeType && in_array($canonicalMimeType, (array) $mimeTypes)) {
1437 * Associates a format with mime types.
1439 * @param string $format The format
1440 * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
1442 public function setFormat($format, $mimeTypes)
1444 if (null === static::$formats) {
1445 static::initializeFormats();
1448 static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
1452 * Gets the request format.
1454 * Here is the process to determine the format:
1456 * * format defined by the user (with setRequestFormat())
1457 * * _format request attribute
1460 * @param string $default The default format
1462 * @return string The request format
1464 public function getRequestFormat($default = 'html')
1466 if (null === $this->format) {
1467 $this->format = $this->attributes->get('_format');
1470 return null === $this->format ? $default : $this->format;
1474 * Sets the request format.
1476 * @param string $format The request format
1478 public function setRequestFormat($format)
1480 $this->format = $format;
1484 * Gets the format associated with the request.
1486 * @return string|null The format (null if no content type is present)
1488 public function getContentType()
1490 return $this->getFormat($this->headers->get('CONTENT_TYPE'));
1494 * Sets the default locale.
1496 * @param string $locale
1498 public function setDefaultLocale($locale)
1500 $this->defaultLocale = $locale;
1502 if (null === $this->locale) {
1503 $this->setPhpDefaultLocale($locale);
1508 * Get the default locale.
1512 public function getDefaultLocale()
1514 return $this->defaultLocale;
1520 * @param string $locale
1522 public function setLocale($locale)
1524 $this->setPhpDefaultLocale($this->locale = $locale);
1532 public function getLocale()
1534 return null === $this->locale ? $this->defaultLocale : $this->locale;
1538 * Checks if the request method is of specified type.
1540 * @param string $method Uppercase request method (GET, POST etc)
1544 public function isMethod($method)
1546 return $this->getMethod() === strtoupper($method);
1550 * Checks whether or not the method is safe.
1552 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1554 * @param bool $andCacheable Adds the additional condition that the method should be cacheable. True by default.
1558 public function isMethodSafe(/* $andCacheable = true */)
1560 if (!func_num_args() || func_get_arg(0)) {
1561 // This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument in the signature)
1562 // then setting $andCacheable to false should be deprecated in 4.1
1563 @trigger_error('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since Symfony 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead.', E_USER_DEPRECATED);
1565 return in_array($this->getMethod(), array('GET', 'HEAD'));
1568 return in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
1572 * Checks whether or not the method is idempotent.
1576 public function isMethodIdempotent()
1578 return in_array($this->getMethod(), array('HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE'));
1582 * Checks whether the method is cacheable or not.
1584 * @see https://tools.ietf.org/html/rfc7231#section-4.2.3
1588 public function isMethodCacheable()
1590 return in_array($this->getMethod(), array('GET', 'HEAD'));
1594 * Returns the protocol version.
1596 * If the application is behind a proxy, the protocol version used in the
1597 * requests between the client and the proxy and between the proxy and the
1598 * server might be different. This returns the former (from the "Via" header)
1599 * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns
1600 * the latter (from the "SERVER_PROTOCOL" server parameter).
1604 public function getProtocolVersion()
1606 if ($this->isFromTrustedProxy()) {
1607 preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via'), $matches);
1610 return 'HTTP/'.$matches[2];
1614 return $this->server->get('SERVER_PROTOCOL');
1618 * Returns the request body content.
1620 * @param bool $asResource If true, a resource will be returned
1622 * @return string|resource The request body content or a resource to read the body stream
1624 * @throws \LogicException
1626 public function getContent($asResource = false)
1628 $currentContentIsResource = is_resource($this->content);
1629 if (\PHP_VERSION_ID < 50600 && false === $this->content) {
1630 throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
1633 if (true === $asResource) {
1634 if ($currentContentIsResource) {
1635 rewind($this->content);
1637 return $this->content;
1640 // Content passed in parameter (test)
1641 if (is_string($this->content)) {
1642 $resource = fopen('php://temp', 'r+');
1643 fwrite($resource, $this->content);
1649 $this->content = false;
1651 return fopen('php://input', 'rb');
1654 if ($currentContentIsResource) {
1655 rewind($this->content);
1657 return stream_get_contents($this->content);
1660 if (null === $this->content || false === $this->content) {
1661 $this->content = file_get_contents('php://input');
1664 return $this->content;
1670 * @return array The entity tags
1672 public function getETags()
1674 return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
1680 public function isNoCache()
1682 return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
1686 * Returns the preferred language.
1688 * @param array $locales An array of ordered available locales
1690 * @return string|null The preferred locale
1692 public function getPreferredLanguage(array $locales = null)
1694 $preferredLanguages = $this->getLanguages();
1696 if (empty($locales)) {
1697 return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
1700 if (!$preferredLanguages) {
1704 $extendedPreferredLanguages = array();
1705 foreach ($preferredLanguages as $language) {
1706 $extendedPreferredLanguages[] = $language;
1707 if (false !== $position = strpos($language, '_')) {
1708 $superLanguage = substr($language, 0, $position);
1709 if (!in_array($superLanguage, $preferredLanguages)) {
1710 $extendedPreferredLanguages[] = $superLanguage;
1715 $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
1717 return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
1721 * Gets a list of languages acceptable by the client browser.
1723 * @return array Languages ordered in the user browser preferences
1725 public function getLanguages()
1727 if (null !== $this->languages) {
1728 return $this->languages;
1731 $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
1732 $this->languages = array();
1733 foreach ($languages as $lang => $acceptHeaderItem) {
1734 if (false !== strpos($lang, '-')) {
1735 $codes = explode('-', $lang);
1736 if ('i' === $codes[0]) {
1737 // Language not listed in ISO 639 that are not variants
1738 // of any listed language, which can be registered with the
1739 // i-prefix, such as i-cherokee
1740 if (count($codes) > 1) {
1744 for ($i = 0, $max = count($codes); $i < $max; ++$i) {
1746 $lang = strtolower($codes[0]);
1748 $lang .= '_'.strtoupper($codes[$i]);
1754 $this->languages[] = $lang;
1757 return $this->languages;
1761 * Gets a list of charsets acceptable by the client browser.
1763 * @return array List of charsets in preferable order
1765 public function getCharsets()
1767 if (null !== $this->charsets) {
1768 return $this->charsets;
1771 return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
1775 * Gets a list of encodings acceptable by the client browser.
1777 * @return array List of encodings in preferable order
1779 public function getEncodings()
1781 if (null !== $this->encodings) {
1782 return $this->encodings;
1785 return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all());
1789 * Gets a list of content types acceptable by the client browser.
1791 * @return array List of content types in preferable order
1793 public function getAcceptableContentTypes()
1795 if (null !== $this->acceptableContentTypes) {
1796 return $this->acceptableContentTypes;
1799 return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
1803 * Returns true if the request is a XMLHttpRequest.
1805 * It works if your JavaScript library sets an X-Requested-With HTTP header.
1806 * It is known to work with common JavaScript frameworks:
1808 * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
1810 * @return bool true if the request is an XMLHttpRequest, false otherwise
1812 public function isXmlHttpRequest()
1814 return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
1818 * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
1820 * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
1822 * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
1825 protected function prepareRequestUri()
1829 if ($this->headers->has('X_ORIGINAL_URL')) {
1830 // IIS with Microsoft Rewrite Module
1831 $requestUri = $this->headers->get('X_ORIGINAL_URL');
1832 $this->headers->remove('X_ORIGINAL_URL');
1833 $this->server->remove('HTTP_X_ORIGINAL_URL');
1834 $this->server->remove('UNENCODED_URL');
1835 $this->server->remove('IIS_WasUrlRewritten');
1836 } elseif ($this->headers->has('X_REWRITE_URL')) {
1837 // IIS with ISAPI_Rewrite
1838 $requestUri = $this->headers->get('X_REWRITE_URL');
1839 $this->headers->remove('X_REWRITE_URL');
1840 } elseif ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) {
1841 // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
1842 $requestUri = $this->server->get('UNENCODED_URL');
1843 $this->server->remove('UNENCODED_URL');
1844 $this->server->remove('IIS_WasUrlRewritten');
1845 } elseif ($this->server->has('REQUEST_URI')) {
1846 $requestUri = $this->server->get('REQUEST_URI');
1847 // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path
1848 $schemeAndHttpHost = $this->getSchemeAndHttpHost();
1849 if (0 === strpos($requestUri, $schemeAndHttpHost)) {
1850 $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
1852 } elseif ($this->server->has('ORIG_PATH_INFO')) {
1853 // IIS 5.0, PHP as CGI
1854 $requestUri = $this->server->get('ORIG_PATH_INFO');
1855 if ('' != $this->server->get('QUERY_STRING')) {
1856 $requestUri .= '?'.$this->server->get('QUERY_STRING');
1858 $this->server->remove('ORIG_PATH_INFO');
1861 // normalize the request URI to ease creating sub-requests from this request
1862 $this->server->set('REQUEST_URI', $requestUri);
1868 * Prepares the base URL.
1872 protected function prepareBaseUrl()
1874 $filename = basename($this->server->get('SCRIPT_FILENAME'));
1876 if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
1877 $baseUrl = $this->server->get('SCRIPT_NAME');
1878 } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
1879 $baseUrl = $this->server->get('PHP_SELF');
1880 } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
1881 $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
1883 // Backtrack up the script_filename to find the portion matching
1885 $path = $this->server->get('PHP_SELF', '');
1886 $file = $this->server->get('SCRIPT_FILENAME', '');
1887 $segs = explode('/', trim($file, '/'));
1888 $segs = array_reverse($segs);
1890 $last = count($segs);
1893 $seg = $segs[$index];
1894 $baseUrl = '/'.$seg.$baseUrl;
1896 } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
1899 // Does the baseUrl have anything in common with the request_uri?
1900 $requestUri = $this->getRequestUri();
1901 if ('' !== $requestUri && '/' !== $requestUri[0]) {
1902 $requestUri = '/'.$requestUri;
1905 if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
1906 // full $baseUrl matches
1910 if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(dirname($baseUrl), '/'.DIRECTORY_SEPARATOR).'/')) {
1911 // directory portion of $baseUrl matches
1912 return rtrim($prefix, '/'.DIRECTORY_SEPARATOR);
1915 $truncatedRequestUri = $requestUri;
1916 if (false !== $pos = strpos($requestUri, '?')) {
1917 $truncatedRequestUri = substr($requestUri, 0, $pos);
1920 $basename = basename($baseUrl);
1921 if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
1922 // no match whatsoever; set it blank
1926 // If using mod_rewrite or ISAPI_Rewrite strip the script filename
1927 // out of baseUrl. $pos !== 0 makes sure it is not matching a value
1928 // from PATH_INFO or QUERY_STRING
1929 if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) {
1930 $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
1933 return rtrim($baseUrl, '/'.DIRECTORY_SEPARATOR);
1937 * Prepares the base path.
1939 * @return string base path
1941 protected function prepareBasePath()
1943 $baseUrl = $this->getBaseUrl();
1944 if (empty($baseUrl)) {
1948 $filename = basename($this->server->get('SCRIPT_FILENAME'));
1949 if (basename($baseUrl) === $filename) {
1950 $basePath = dirname($baseUrl);
1952 $basePath = $baseUrl;
1955 if ('\\' === DIRECTORY_SEPARATOR) {
1956 $basePath = str_replace('\\', '/', $basePath);
1959 return rtrim($basePath, '/');
1963 * Prepares the path info.
1965 * @return string path info
1967 protected function preparePathInfo()
1969 if (null === ($requestUri = $this->getRequestUri())) {
1973 // Remove the query string from REQUEST_URI
1974 if (false !== $pos = strpos($requestUri, '?')) {
1975 $requestUri = substr($requestUri, 0, $pos);
1977 if ('' !== $requestUri && '/' !== $requestUri[0]) {
1978 $requestUri = '/'.$requestUri;
1981 if (null === ($baseUrl = $this->getBaseUrl())) {
1985 $pathInfo = substr($requestUri, strlen($baseUrl));
1986 if (false === $pathInfo || '' === $pathInfo) {
1987 // If substr() returns false then PATH_INFO is set to an empty string
1991 return (string) $pathInfo;
1995 * Initializes HTTP request formats.
1997 protected static function initializeFormats()
1999 static::$formats = array(
2000 'html' => array('text/html', 'application/xhtml+xml'),
2001 'txt' => array('text/plain'),
2002 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
2003 'css' => array('text/css'),
2004 'json' => array('application/json', 'application/x-json'),
2005 'jsonld' => array('application/ld+json'),
2006 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
2007 'rdf' => array('application/rdf+xml'),
2008 'atom' => array('application/atom+xml'),
2009 'rss' => array('application/rss+xml'),
2010 'form' => array('application/x-www-form-urlencoded'),
2015 * Sets the default PHP locale.
2017 * @param string $locale
2019 private function setPhpDefaultLocale($locale)
2021 // if either the class Locale doesn't exist, or an exception is thrown when
2022 // setting the default locale, the intl module is not installed, and
2023 // the call can be ignored:
2025 if (class_exists('Locale', false)) {
2026 \Locale::setDefault($locale);
2028 } catch (\Exception $e) {
2033 * Returns the prefix as encoded in the string when the string starts with
2034 * the given prefix, false otherwise.
2036 * @param string $string The urlencoded string
2037 * @param string $prefix The prefix not encoded
2039 * @return string|false The prefix as it is encoded in $string, or false
2041 private function getUrlencodedPrefix($string, $prefix)
2043 if (0 !== strpos(rawurldecode($string), $prefix)) {
2047 $len = strlen($prefix);
2049 if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
2056 private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
2058 if (self::$requestFactory) {
2059 $request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
2061 if (!$request instanceof self) {
2062 throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
2068 return new static($query, $request, $attributes, $cookies, $files, $server, $content);
2072 * Indicates whether this request originated from a trusted proxy.
2074 * This can be useful to determine whether or not to trust the
2075 * contents of a proxy-specific header.
2077 * @return bool true if the request came from a trusted proxy, false otherwise
2079 public function isFromTrustedProxy()
2081 return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies);
2084 private function getTrustedValues($type, $ip = null)
2086 $clientValues = array();
2087 $forwardedValues = array();
2089 if (self::$trustedHeaders[$type] && $this->headers->has(self::$trustedHeaders[$type])) {
2090 foreach (explode(',', $this->headers->get(self::$trustedHeaders[$type])) as $v) {
2091 $clientValues[] = (self::HEADER_CLIENT_PORT === $type ? '0.0.0.0:' : '').trim($v);
2095 if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) {
2096 $forwardedValues = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]);
2097 $forwardedValues = preg_match_all(sprintf('{(?:%s)=(?:"?\[?)([a-zA-Z0-9\.:_\-/]*+)}', self::$forwardedParams[$type]), $forwardedValues, $matches) ? $matches[1] : array();
2101 $clientValues = $this->normalizeAndFilterClientIps($clientValues, $ip);
2102 $forwardedValues = $this->normalizeAndFilterClientIps($forwardedValues, $ip);
2105 if ($forwardedValues === $clientValues || !$clientValues) {
2106 return $forwardedValues;
2109 if (!$forwardedValues) {
2110 return $clientValues;
2113 if (!$this->isForwardedValid) {
2114 return null !== $ip ? array('0.0.0.0', $ip) : array();
2116 $this->isForwardedValid = false;
2118 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::$trustedHeaders[self::HEADER_FORWARDED], self::$trustedHeaders[$type]));
2121 private function normalizeAndFilterClientIps(array $clientIps, $ip)
2126 $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
2127 $firstTrustedIp = null;
2129 foreach ($clientIps as $key => $clientIp) {
2130 // Remove port (unfortunately, it does happen)
2131 if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) {
2132 $clientIps[$key] = $clientIp = $match[1];
2135 if (!filter_var($clientIp, FILTER_VALIDATE_IP)) {
2136 unset($clientIps[$key]);
2141 if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
2142 unset($clientIps[$key]);
2144 // Fallback to this when the client IP falls into the range of trusted proxies
2145 if (null === $firstTrustedIp) {
2146 $firstTrustedIp = $clientIp;
2151 // Now the IP chain contains only untrusted proxies and the client IP
2152 return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp);