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\Session\SessionInterface;
18 * Request represents an HTTP request.
20 * The methods dealing with URL accept / return a raw path (% encoded):
28 * @author Fabien Potencier <fabien@symfony.com>
32 const HEADER_FORWARDED = 'forwarded';
33 const HEADER_CLIENT_IP = 'client_ip';
34 const HEADER_CLIENT_HOST = 'client_host';
35 const HEADER_CLIENT_PROTO = 'client_proto';
36 const HEADER_CLIENT_PORT = 'client_port';
38 const METHOD_HEAD = 'HEAD';
39 const METHOD_GET = 'GET';
40 const METHOD_POST = 'POST';
41 const METHOD_PUT = 'PUT';
42 const METHOD_PATCH = 'PATCH';
43 const METHOD_DELETE = 'DELETE';
44 const METHOD_PURGE = 'PURGE';
45 const METHOD_OPTIONS = 'OPTIONS';
46 const METHOD_TRACE = 'TRACE';
47 const METHOD_CONNECT = 'CONNECT';
52 protected static $trustedProxies = array();
57 protected static $trustedHostPatterns = array();
62 protected static $trustedHosts = array();
65 * Names for headers that can be trusted when
66 * using trusted proxies.
68 * The FORWARDED header is the standard as of rfc7239.
70 * The other headers are non-standard, but widely used
71 * by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
73 protected static $trustedHeaders = array(
74 self::HEADER_FORWARDED => 'FORWARDED',
75 self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',
76 self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST',
77 self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
78 self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT',
81 protected static $httpMethodParameterOverride = false;
86 * @var \Symfony\Component\HttpFoundation\ParameterBag
91 * Request body parameters ($_POST).
93 * @var \Symfony\Component\HttpFoundation\ParameterBag
98 * Query string parameters ($_GET).
100 * @var \Symfony\Component\HttpFoundation\ParameterBag
105 * Server and execution environment parameters ($_SERVER).
107 * @var \Symfony\Component\HttpFoundation\ServerBag
112 * Uploaded files ($_FILES).
114 * @var \Symfony\Component\HttpFoundation\FileBag
119 * Cookies ($_COOKIE).
121 * @var \Symfony\Component\HttpFoundation\ParameterBag
126 * Headers (taken from the $_SERVER).
128 * @var \Symfony\Component\HttpFoundation\HeaderBag
140 protected $languages;
150 protected $encodings;
155 protected $acceptableContentTypes;
165 protected $requestUri;
188 * @var \Symfony\Component\HttpFoundation\Session\SessionInterface
200 protected $defaultLocale = 'en';
205 protected static $formats;
207 protected static $requestFactory;
209 private $isForwardedValid = true;
211 private static $forwardedParams = array(
212 self::HEADER_CLIENT_IP => 'for',
213 self::HEADER_CLIENT_HOST => 'host',
214 self::HEADER_CLIENT_PROTO => 'proto',
215 self::HEADER_CLIENT_PORT => 'host',
221 * @param array $query The GET parameters
222 * @param array $request The POST parameters
223 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
224 * @param array $cookies The COOKIE parameters
225 * @param array $files The FILES parameters
226 * @param array $server The SERVER parameters
227 * @param string|resource $content The raw body data
229 public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
231 $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
235 * Sets the parameters for this request.
237 * This method also re-initializes all properties.
239 * @param array $query The GET parameters
240 * @param array $request The POST parameters
241 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
242 * @param array $cookies The COOKIE parameters
243 * @param array $files The FILES parameters
244 * @param array $server The SERVER parameters
245 * @param string|resource $content The raw body data
247 public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
249 $this->request = new ParameterBag($request);
250 $this->query = new ParameterBag($query);
251 $this->attributes = new ParameterBag($attributes);
252 $this->cookies = new ParameterBag($cookies);
253 $this->files = new FileBag($files);
254 $this->server = new ServerBag($server);
255 $this->headers = new HeaderBag($this->server->getHeaders());
257 $this->content = $content;
258 $this->languages = null;
259 $this->charsets = null;
260 $this->encodings = null;
261 $this->acceptableContentTypes = null;
262 $this->pathInfo = null;
263 $this->requestUri = null;
264 $this->baseUrl = null;
265 $this->basePath = null;
266 $this->method = null;
267 $this->format = null;
271 * Creates a new request with values from PHP's super globals.
275 public static function createFromGlobals()
277 // With the php's bug #66606, the php's built-in web server
278 // stores the Content-Type and Content-Length header values in
279 // HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields.
281 if ('cli-server' === PHP_SAPI) {
282 if (array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) {
283 $server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH'];
285 if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) {
286 $server['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE'];
290 $request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $server);
292 if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
293 && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
295 parse_str($request->getContent(), $data);
296 $request->request = new ParameterBag($data);
303 * Creates a Request based on a given URI and configuration.
305 * The information contained in the URI always take precedence
306 * over the other information (server and parameters).
308 * @param string $uri The URI
309 * @param string $method The HTTP method
310 * @param array $parameters The query (GET) or request (POST) parameters
311 * @param array $cookies The request cookies ($_COOKIE)
312 * @param array $files The request files ($_FILES)
313 * @param array $server The server parameters ($_SERVER)
314 * @param string $content The raw body data
318 public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
320 $server = array_replace(array(
321 'SERVER_NAME' => 'localhost',
323 'HTTP_HOST' => 'localhost',
324 'HTTP_USER_AGENT' => 'Symfony/3.X',
325 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
326 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
327 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
328 'REMOTE_ADDR' => '127.0.0.1',
330 'SCRIPT_FILENAME' => '',
331 'SERVER_PROTOCOL' => 'HTTP/1.1',
332 'REQUEST_TIME' => time(),
335 $server['PATH_INFO'] = '';
336 $server['REQUEST_METHOD'] = strtoupper($method);
338 $components = parse_url($uri);
339 if (isset($components['host'])) {
340 $server['SERVER_NAME'] = $components['host'];
341 $server['HTTP_HOST'] = $components['host'];
344 if (isset($components['scheme'])) {
345 if ('https' === $components['scheme']) {
346 $server['HTTPS'] = 'on';
347 $server['SERVER_PORT'] = 443;
349 unset($server['HTTPS']);
350 $server['SERVER_PORT'] = 80;
354 if (isset($components['port'])) {
355 $server['SERVER_PORT'] = $components['port'];
356 $server['HTTP_HOST'] = $server['HTTP_HOST'].':'.$components['port'];
359 if (isset($components['user'])) {
360 $server['PHP_AUTH_USER'] = $components['user'];
363 if (isset($components['pass'])) {
364 $server['PHP_AUTH_PW'] = $components['pass'];
367 if (!isset($components['path'])) {
368 $components['path'] = '/';
371 switch (strtoupper($method)) {
375 if (!isset($server['CONTENT_TYPE'])) {
376 $server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
380 $request = $parameters;
385 $query = $parameters;
390 if (isset($components['query'])) {
391 parse_str(html_entity_decode($components['query']), $qs);
394 $query = array_replace($qs, $query);
395 $queryString = http_build_query($query, '', '&');
398 $queryString = $components['query'];
401 $queryString = http_build_query($query, '', '&');
404 $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : '');
405 $server['QUERY_STRING'] = $queryString;
407 return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content);
411 * Sets a callable able to create a Request instance.
413 * This is mainly useful when you need to override the Request class
414 * to keep BC with an existing system. It should not be used for any
417 * @param callable|null $callable A PHP callable
419 public static function setFactory($callable)
421 self::$requestFactory = $callable;
425 * Clones a request and overrides some of its parameters.
427 * @param array $query The GET parameters
428 * @param array $request The POST parameters
429 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
430 * @param array $cookies The COOKIE parameters
431 * @param array $files The FILES parameters
432 * @param array $server The SERVER parameters
436 public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
439 if ($query !== null) {
440 $dup->query = new ParameterBag($query);
442 if ($request !== null) {
443 $dup->request = new ParameterBag($request);
445 if ($attributes !== null) {
446 $dup->attributes = new ParameterBag($attributes);
448 if ($cookies !== null) {
449 $dup->cookies = new ParameterBag($cookies);
451 if ($files !== null) {
452 $dup->files = new FileBag($files);
454 if ($server !== null) {
455 $dup->server = new ServerBag($server);
456 $dup->headers = new HeaderBag($dup->server->getHeaders());
458 $dup->languages = null;
459 $dup->charsets = null;
460 $dup->encodings = null;
461 $dup->acceptableContentTypes = null;
462 $dup->pathInfo = null;
463 $dup->requestUri = null;
464 $dup->baseUrl = null;
465 $dup->basePath = null;
469 if (!$dup->get('_format') && $this->get('_format')) {
470 $dup->attributes->set('_format', $this->get('_format'));
473 if (!$dup->getRequestFormat(null)) {
474 $dup->setRequestFormat($this->getRequestFormat(null));
481 * Clones the current request.
483 * Note that the session is not cloned as duplicated requests
484 * are most of the time sub-requests of the main one.
486 public function __clone()
488 $this->query = clone $this->query;
489 $this->request = clone $this->request;
490 $this->attributes = clone $this->attributes;
491 $this->cookies = clone $this->cookies;
492 $this->files = clone $this->files;
493 $this->server = clone $this->server;
494 $this->headers = clone $this->headers;
498 * Returns the request as a string.
500 * @return string The request
502 public function __toString()
505 $content = $this->getContent();
506 } catch (\LogicException $e) {
507 return trigger_error($e, E_USER_ERROR);
511 sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
512 $this->headers."\r\n".
517 * Overrides the PHP global variables according to this request instance.
519 * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE.
520 * $_FILES is never overridden, see rfc1867
522 public function overrideGlobals()
524 $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), null, '&')));
526 $_GET = $this->query->all();
527 $_POST = $this->request->all();
528 $_SERVER = $this->server->all();
529 $_COOKIE = $this->cookies->all();
531 foreach ($this->headers->all() as $key => $value) {
532 $key = strtoupper(str_replace('-', '_', $key));
533 if (in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
534 $_SERVER[$key] = implode(', ', $value);
536 $_SERVER['HTTP_'.$key] = implode(', ', $value);
540 $request = array('g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE);
542 $requestOrder = ini_get('request_order') ?: ini_get('variables_order');
543 $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp';
546 foreach (str_split($requestOrder) as $order) {
547 $_REQUEST = array_merge($_REQUEST, $request[$order]);
552 * Sets a list of trusted proxies.
554 * You should only list the reverse proxies that you manage directly.
556 * @param array $proxies A list of trusted proxies
558 public static function setTrustedProxies(array $proxies)
560 self::$trustedProxies = $proxies;
564 * Gets the list of trusted proxies.
566 * @return array An array of trusted proxies
568 public static function getTrustedProxies()
570 return self::$trustedProxies;
574 * Sets a list of trusted host patterns.
576 * You should only list the hosts you manage using regexs.
578 * @param array $hostPatterns A list of trusted host patterns
580 public static function setTrustedHosts(array $hostPatterns)
582 self::$trustedHostPatterns = array_map(function ($hostPattern) {
583 return sprintf('#%s#i', $hostPattern);
585 // we need to reset trusted hosts on trusted host patterns change
586 self::$trustedHosts = array();
590 * Gets the list of trusted host patterns.
592 * @return array An array of trusted host patterns
594 public static function getTrustedHosts()
596 return self::$trustedHostPatterns;
600 * Sets the name for trusted headers.
602 * The following header keys are supported:
604 * * Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp())
605 * * Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getHost())
606 * * Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getPort())
607 * * Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure())
608 * * Request::HEADER_FORWARDED: defaults to Forwarded (see RFC 7239)
610 * Setting an empty value allows to disable the trusted header for the given key.
612 * @param string $key The header key
613 * @param string $value The header name
615 * @throws \InvalidArgumentException
617 public static function setTrustedHeaderName($key, $value)
619 if (!array_key_exists($key, self::$trustedHeaders)) {
620 throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key));
623 self::$trustedHeaders[$key] = $value;
627 * Gets the trusted proxy header name.
629 * @param string $key The header key
631 * @return string The header name
633 * @throws \InvalidArgumentException
635 public static function getTrustedHeaderName($key)
637 if (!array_key_exists($key, self::$trustedHeaders)) {
638 throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key));
641 return self::$trustedHeaders[$key];
645 * Normalizes a query string.
647 * It builds a normalized query string, where keys/value pairs are alphabetized,
648 * have consistent escaping and unneeded delimiters are removed.
650 * @param string $qs Query string
652 * @return string A normalized query string for the Request
654 public static function normalizeQueryString($qs)
663 foreach (explode('&', $qs) as $param) {
664 if ('' === $param || '=' === $param[0]) {
665 // Ignore useless delimiters, e.g. "x=y&".
666 // Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
667 // PHP also does not include them when building _GET.
671 $keyValuePair = explode('=', $param, 2);
673 // GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
674 // 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
675 // RFC 3986 with rawurlencode.
676 $parts[] = isset($keyValuePair[1]) ?
677 rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
678 rawurlencode(urldecode($keyValuePair[0]));
679 $order[] = urldecode($keyValuePair[0]);
682 array_multisort($order, SORT_ASC, $parts);
684 return implode('&', $parts);
688 * Enables support for the _method request parameter to determine the intended HTTP method.
690 * Be warned that enabling this feature might lead to CSRF issues in your code.
691 * Check that you are using CSRF tokens when required.
692 * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered
693 * and used to send a "PUT" or "DELETE" request via the _method request parameter.
694 * If these methods are not protected against CSRF, this presents a possible vulnerability.
696 * The HTTP method can only be overridden when the real HTTP method is POST.
698 public static function enableHttpMethodParameterOverride()
700 self::$httpMethodParameterOverride = true;
704 * Checks whether support for the _method request parameter is enabled.
706 * @return bool True when the _method request parameter is enabled, false otherwise
708 public static function getHttpMethodParameterOverride()
710 return self::$httpMethodParameterOverride;
714 * Gets a "parameter" value from any bag.
716 * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the
717 * flexibility in controllers, it is better to explicitly get request parameters from the appropriate
718 * public property instead (attributes, query, request).
720 * Order of precedence: PATH (routing placeholders or custom attributes), GET, BODY
722 * @param string $key the key
723 * @param mixed $default the default value if the parameter key does not exist
727 public function get($key, $default = null)
729 if ($this !== $result = $this->attributes->get($key, $this)) {
733 if ($this !== $result = $this->query->get($key, $this)) {
737 if ($this !== $result = $this->request->get($key, $this)) {
747 * @return SessionInterface|null The session
749 public function getSession()
751 return $this->session;
755 * Whether the request contains a Session which was started in one of the
760 public function hasPreviousSession()
762 // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
763 return $this->hasSession() && $this->cookies->has($this->session->getName());
767 * Whether the request contains a Session object.
769 * This method does not give any information about the state of the session object,
770 * like whether the session is started or not. It is just a way to check if this Request
771 * is associated with a Session instance.
773 * @return bool true when the Request contains a Session object, false otherwise
775 public function hasSession()
777 return null !== $this->session;
783 * @param SessionInterface $session The Session
785 public function setSession(SessionInterface $session)
787 $this->session = $session;
791 * Returns the client IP addresses.
793 * In the returned array the most trusted IP address is first, and the
794 * least trusted one last. The "real" client IP address is the last one,
795 * but this is also the least trusted one. Trusted proxies are stripped.
797 * Use this method carefully; you should use getClientIp() instead.
799 * @return array The client IP addresses
803 public function getClientIps()
805 $ip = $this->server->get('REMOTE_ADDR');
807 if (!$this->isFromTrustedProxy()) {
811 return $this->getTrustedValues(self::HEADER_CLIENT_IP, $ip) ?: array($ip);
815 * Returns the client IP address.
817 * This method can read the client IP address from the "X-Forwarded-For" header
818 * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
819 * header value is a comma+space separated list of IP addresses, the left-most
820 * being the original client, and each successive proxy that passed the request
821 * adding the IP address where it received the request from.
823 * If your reverse proxy uses a different header name than "X-Forwarded-For",
824 * ("Client-Ip" for instance), configure it via "setTrustedHeaderName()" with
825 * the "client-ip" key.
827 * @return string|null The client IP address
829 * @see getClientIps()
830 * @see http://en.wikipedia.org/wiki/X-Forwarded-For
832 public function getClientIp()
834 $ipAddresses = $this->getClientIps();
836 return $ipAddresses[0];
840 * Returns current script name.
844 public function getScriptName()
846 return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
850 * Returns the path being requested relative to the executed script.
852 * The path info always starts with a /.
854 * Suppose this request is instantiated from /mysite on localhost:
856 * * http://localhost/mysite returns an empty string
857 * * http://localhost/mysite/about returns '/about'
858 * * http://localhost/mysite/enco%20ded returns '/enco%20ded'
859 * * http://localhost/mysite/about?var=1 returns '/about'
861 * @return string The raw path (i.e. not urldecoded)
863 public function getPathInfo()
865 if (null === $this->pathInfo) {
866 $this->pathInfo = $this->preparePathInfo();
869 return $this->pathInfo;
873 * Returns the root path from which this request is executed.
875 * Suppose that an index.php file instantiates this request object:
877 * * http://localhost/index.php returns an empty string
878 * * http://localhost/index.php/page returns an empty string
879 * * http://localhost/web/index.php returns '/web'
880 * * http://localhost/we%20b/index.php returns '/we%20b'
882 * @return string The raw path (i.e. not urldecoded)
884 public function getBasePath()
886 if (null === $this->basePath) {
887 $this->basePath = $this->prepareBasePath();
890 return $this->basePath;
894 * Returns the root URL from which this request is executed.
896 * The base URL never ends with a /.
898 * This is similar to getBasePath(), except that it also includes the
899 * script filename (e.g. index.php) if one exists.
901 * @return string The raw URL (i.e. not urldecoded)
903 public function getBaseUrl()
905 if (null === $this->baseUrl) {
906 $this->baseUrl = $this->prepareBaseUrl();
909 return $this->baseUrl;
913 * Gets the request's scheme.
917 public function getScheme()
919 return $this->isSecure() ? 'https' : 'http';
923 * Returns the port on which the request is made.
925 * This method can read the client port from the "X-Forwarded-Port" header
926 * when trusted proxies were set via "setTrustedProxies()".
928 * The "X-Forwarded-Port" header must contain the client port.
930 * If your reverse proxy uses a different header name than "X-Forwarded-Port",
931 * configure it via "setTrustedHeaderName()" with the "client-port" key.
933 * @return int|string can be a string if fetched from the server bag
935 public function getPort()
937 if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_PORT)) {
939 } elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_HOST)) {
941 } elseif (!$host = $this->headers->get('HOST')) {
942 return $this->server->get('SERVER_PORT');
945 if ($host[0] === '[') {
946 $pos = strpos($host, ':', strrpos($host, ']'));
948 $pos = strrpos($host, ':');
951 if (false !== $pos) {
952 return (int) substr($host, $pos + 1);
955 return 'https' === $this->getScheme() ? 443 : 80;
961 * @return string|null
963 public function getUser()
965 return $this->headers->get('PHP_AUTH_USER');
969 * Returns the password.
971 * @return string|null
973 public function getPassword()
975 return $this->headers->get('PHP_AUTH_PW');
979 * Gets the user info.
981 * @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server
983 public function getUserInfo()
985 $userinfo = $this->getUser();
987 $pass = $this->getPassword();
989 $userinfo .= ":$pass";
996 * Returns the HTTP host being requested.
998 * The port name will be appended to the host if it's non-standard.
1002 public function getHttpHost()
1004 $scheme = $this->getScheme();
1005 $port = $this->getPort();
1007 if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
1008 return $this->getHost();
1011 return $this->getHost().':'.$port;
1015 * Returns the requested URI (path and query string).
1017 * @return string The raw URI (i.e. not URI decoded)
1019 public function getRequestUri()
1021 if (null === $this->requestUri) {
1022 $this->requestUri = $this->prepareRequestUri();
1025 return $this->requestUri;
1029 * Gets the scheme and HTTP host.
1031 * If the URL was called with basic authentication, the user
1032 * and the password are not added to the generated string.
1034 * @return string The scheme and HTTP host
1036 public function getSchemeAndHttpHost()
1038 return $this->getScheme().'://'.$this->getHttpHost();
1042 * Generates a normalized URI (URL) for the Request.
1044 * @return string A normalized URI (URL) for the Request
1046 * @see getQueryString()
1048 public function getUri()
1050 if (null !== $qs = $this->getQueryString()) {
1054 return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
1058 * Generates a normalized URI for the given path.
1060 * @param string $path A path to use instead of the current one
1062 * @return string The normalized URI for the path
1064 public function getUriForPath($path)
1066 return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
1070 * Returns the path as relative reference from the current Request path.
1072 * Only the URIs path component (no schema, host etc.) is relevant and must be given.
1073 * Both paths must be absolute and not contain relative parts.
1074 * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
1075 * Furthermore, they can be used to reduce the link size in documents.
1077 * Example target paths, given a base path of "/a/b/c/d":
1078 * - "/a/b/c/d" -> ""
1079 * - "/a/b/c/" -> "./"
1080 * - "/a/b/" -> "../"
1081 * - "/a/b/c/other" -> "other"
1082 * - "/a/x/y" -> "../../x/y"
1084 * @param string $path The target path
1086 * @return string The relative target path
1088 public function getRelativeUriForPath($path)
1090 // be sure that we are dealing with an absolute path
1091 if (!isset($path[0]) || '/' !== $path[0]) {
1095 if ($path === $basePath = $this->getPathInfo()) {
1099 $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
1100 $targetDirs = explode('/', isset($path[0]) && '/' === $path[0] ? substr($path, 1) : $path);
1101 array_pop($sourceDirs);
1102 $targetFile = array_pop($targetDirs);
1104 foreach ($sourceDirs as $i => $dir) {
1105 if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
1106 unset($sourceDirs[$i], $targetDirs[$i]);
1112 $targetDirs[] = $targetFile;
1113 $path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
1115 // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
1116 // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
1117 // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
1118 // (see http://tools.ietf.org/html/rfc3986#section-4.2).
1119 return !isset($path[0]) || '/' === $path[0]
1120 || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
1121 ? "./$path" : $path;
1125 * Generates the normalized query string for the Request.
1127 * It builds a normalized query string, where keys/value pairs are alphabetized
1128 * and have consistent escaping.
1130 * @return string|null A normalized query string for the Request
1132 public function getQueryString()
1134 $qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
1136 return '' === $qs ? null : $qs;
1140 * Checks whether the request is secure or not.
1142 * This method can read the client protocol from the "X-Forwarded-Proto" header
1143 * when trusted proxies were set via "setTrustedProxies()".
1145 * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
1147 * If your reverse proxy uses a different header name than "X-Forwarded-Proto"
1148 * ("SSL_HTTPS" for instance), configure it via "setTrustedHeaderName()" with
1149 * the "client-proto" key.
1153 public function isSecure()
1155 if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_CLIENT_PROTO)) {
1156 return in_array(strtolower($proto[0]), array('https', 'on', 'ssl', '1'), true);
1159 $https = $this->server->get('HTTPS');
1161 return !empty($https) && 'off' !== strtolower($https);
1165 * Returns the host name.
1167 * This method can read the client host name from the "X-Forwarded-Host" header
1168 * when trusted proxies were set via "setTrustedProxies()".
1170 * The "X-Forwarded-Host" header must contain the client host name.
1172 * If your reverse proxy uses a different header name than "X-Forwarded-Host",
1173 * configure it via "setTrustedHeaderName()" with the "client-host" key.
1177 * @throws \UnexpectedValueException when the host name is invalid
1179 public function getHost()
1181 if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_HOST)) {
1183 } elseif (!$host = $this->headers->get('HOST')) {
1184 if (!$host = $this->server->get('SERVER_NAME')) {
1185 $host = $this->server->get('SERVER_ADDR', '');
1189 // trim and remove port number from host
1190 // host is lowercase as per RFC 952/2181
1191 $host = strtolower(preg_replace('/:\d+$/', '', trim($host)));
1193 // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
1194 // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
1195 // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
1196 if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
1197 throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
1200 if (count(self::$trustedHostPatterns) > 0) {
1201 // to avoid host header injection attacks, you should provide a list of trusted host patterns
1203 if (in_array($host, self::$trustedHosts)) {
1207 foreach (self::$trustedHostPatterns as $pattern) {
1208 if (preg_match($pattern, $host)) {
1209 self::$trustedHosts[] = $host;
1215 throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host));
1222 * Sets the request method.
1224 * @param string $method
1226 public function setMethod($method)
1228 $this->method = null;
1229 $this->server->set('REQUEST_METHOD', $method);
1233 * Gets the request "intended" method.
1235 * If the X-HTTP-Method-Override header is set, and if the method is a POST,
1236 * then it is used to determine the "real" intended HTTP method.
1238 * The _method request parameter can also be used to determine the HTTP method,
1239 * but only if enableHttpMethodParameterOverride() has been called.
1241 * The method is always an uppercased string.
1243 * @return string The request method
1245 * @see getRealMethod()
1247 public function getMethod()
1249 if (null === $this->method) {
1250 $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
1252 if ('POST' === $this->method) {
1253 if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
1254 $this->method = strtoupper($method);
1255 } elseif (self::$httpMethodParameterOverride) {
1256 $this->method = strtoupper($this->request->get('_method', $this->query->get('_method', 'POST')));
1261 return $this->method;
1265 * Gets the "real" request method.
1267 * @return string The request method
1271 public function getRealMethod()
1273 return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
1277 * Gets the mime type associated with the format.
1279 * @param string $format The format
1281 * @return string The associated mime type (null if not found)
1283 public function getMimeType($format)
1285 if (null === static::$formats) {
1286 static::initializeFormats();
1289 return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
1293 * Gets the mime types associated with the format.
1295 * @param string $format The format
1297 * @return array The associated mime types
1299 public static function getMimeTypes($format)
1301 if (null === static::$formats) {
1302 static::initializeFormats();
1305 return isset(static::$formats[$format]) ? static::$formats[$format] : array();
1309 * Gets the format associated with the mime type.
1311 * @param string $mimeType The associated mime type
1313 * @return string|null The format (null if not found)
1315 public function getFormat($mimeType)
1317 $canonicalMimeType = null;
1318 if (false !== $pos = strpos($mimeType, ';')) {
1319 $canonicalMimeType = substr($mimeType, 0, $pos);
1322 if (null === static::$formats) {
1323 static::initializeFormats();
1326 foreach (static::$formats as $format => $mimeTypes) {
1327 if (in_array($mimeType, (array) $mimeTypes)) {
1330 if (null !== $canonicalMimeType && in_array($canonicalMimeType, (array) $mimeTypes)) {
1337 * Associates a format with mime types.
1339 * @param string $format The format
1340 * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
1342 public function setFormat($format, $mimeTypes)
1344 if (null === static::$formats) {
1345 static::initializeFormats();
1348 static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
1352 * Gets the request format.
1354 * Here is the process to determine the format:
1356 * * format defined by the user (with setRequestFormat())
1357 * * _format request attribute
1360 * @param string $default The default format
1362 * @return string The request format
1364 public function getRequestFormat($default = 'html')
1366 if (null === $this->format) {
1367 $this->format = $this->attributes->get('_format');
1370 return null === $this->format ? $default : $this->format;
1374 * Sets the request format.
1376 * @param string $format The request format
1378 public function setRequestFormat($format)
1380 $this->format = $format;
1384 * Gets the format associated with the request.
1386 * @return string|null The format (null if no content type is present)
1388 public function getContentType()
1390 return $this->getFormat($this->headers->get('CONTENT_TYPE'));
1394 * Sets the default locale.
1396 * @param string $locale
1398 public function setDefaultLocale($locale)
1400 $this->defaultLocale = $locale;
1402 if (null === $this->locale) {
1403 $this->setPhpDefaultLocale($locale);
1408 * Get the default locale.
1412 public function getDefaultLocale()
1414 return $this->defaultLocale;
1420 * @param string $locale
1422 public function setLocale($locale)
1424 $this->setPhpDefaultLocale($this->locale = $locale);
1432 public function getLocale()
1434 return null === $this->locale ? $this->defaultLocale : $this->locale;
1438 * Checks if the request method is of specified type.
1440 * @param string $method Uppercase request method (GET, POST etc)
1444 public function isMethod($method)
1446 return $this->getMethod() === strtoupper($method);
1450 * Checks whether or not the method is safe.
1452 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
1454 * @param bool $andCacheable Adds the additional condition that the method should be cacheable. True by default.
1458 public function isMethodSafe(/* $andCacheable = true */)
1460 if (!func_num_args() || func_get_arg(0)) {
1461 // This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument in the signature)
1462 // then setting $andCacheable to false should be deprecated in 4.1
1463 @trigger_error('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since version 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);
1465 return in_array($this->getMethod(), array('GET', 'HEAD'));
1468 return in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
1472 * Checks whether or not the method is idempotent.
1476 public function isMethodIdempotent()
1478 return in_array($this->getMethod(), array('HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE'));
1482 * Checks whether the method is cacheable or not.
1484 * @see https://tools.ietf.org/html/rfc7231#section-4.2.3
1488 public function isMethodCacheable()
1490 return in_array($this->getMethod(), array('GET', 'HEAD'));
1494 * Returns the request body content.
1496 * @param bool $asResource If true, a resource will be returned
1498 * @return string|resource The request body content or a resource to read the body stream
1500 * @throws \LogicException
1502 public function getContent($asResource = false)
1504 $currentContentIsResource = is_resource($this->content);
1505 if (\PHP_VERSION_ID < 50600 && false === $this->content) {
1506 throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
1509 if (true === $asResource) {
1510 if ($currentContentIsResource) {
1511 rewind($this->content);
1513 return $this->content;
1516 // Content passed in parameter (test)
1517 if (is_string($this->content)) {
1518 $resource = fopen('php://temp', 'r+');
1519 fwrite($resource, $this->content);
1525 $this->content = false;
1527 return fopen('php://input', 'rb');
1530 if ($currentContentIsResource) {
1531 rewind($this->content);
1533 return stream_get_contents($this->content);
1536 if (null === $this->content || false === $this->content) {
1537 $this->content = file_get_contents('php://input');
1540 return $this->content;
1546 * @return array The entity tags
1548 public function getETags()
1550 return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
1556 public function isNoCache()
1558 return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
1562 * Returns the preferred language.
1564 * @param array $locales An array of ordered available locales
1566 * @return string|null The preferred locale
1568 public function getPreferredLanguage(array $locales = null)
1570 $preferredLanguages = $this->getLanguages();
1572 if (empty($locales)) {
1573 return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
1576 if (!$preferredLanguages) {
1580 $extendedPreferredLanguages = array();
1581 foreach ($preferredLanguages as $language) {
1582 $extendedPreferredLanguages[] = $language;
1583 if (false !== $position = strpos($language, '_')) {
1584 $superLanguage = substr($language, 0, $position);
1585 if (!in_array($superLanguage, $preferredLanguages)) {
1586 $extendedPreferredLanguages[] = $superLanguage;
1591 $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
1593 return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
1597 * Gets a list of languages acceptable by the client browser.
1599 * @return array Languages ordered in the user browser preferences
1601 public function getLanguages()
1603 if (null !== $this->languages) {
1604 return $this->languages;
1607 $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
1608 $this->languages = array();
1609 foreach ($languages as $lang => $acceptHeaderItem) {
1610 if (false !== strpos($lang, '-')) {
1611 $codes = explode('-', $lang);
1612 if ('i' === $codes[0]) {
1613 // Language not listed in ISO 639 that are not variants
1614 // of any listed language, which can be registered with the
1615 // i-prefix, such as i-cherokee
1616 if (count($codes) > 1) {
1620 for ($i = 0, $max = count($codes); $i < $max; ++$i) {
1622 $lang = strtolower($codes[0]);
1624 $lang .= '_'.strtoupper($codes[$i]);
1630 $this->languages[] = $lang;
1633 return $this->languages;
1637 * Gets a list of charsets acceptable by the client browser.
1639 * @return array List of charsets in preferable order
1641 public function getCharsets()
1643 if (null !== $this->charsets) {
1644 return $this->charsets;
1647 return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
1651 * Gets a list of encodings acceptable by the client browser.
1653 * @return array List of encodings in preferable order
1655 public function getEncodings()
1657 if (null !== $this->encodings) {
1658 return $this->encodings;
1661 return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all());
1665 * Gets a list of content types acceptable by the client browser.
1667 * @return array List of content types in preferable order
1669 public function getAcceptableContentTypes()
1671 if (null !== $this->acceptableContentTypes) {
1672 return $this->acceptableContentTypes;
1675 return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
1679 * Returns true if the request is a XMLHttpRequest.
1681 * It works if your JavaScript library sets an X-Requested-With HTTP header.
1682 * It is known to work with common JavaScript frameworks:
1684 * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
1686 * @return bool true if the request is an XMLHttpRequest, false otherwise
1688 public function isXmlHttpRequest()
1690 return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
1694 * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
1696 * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
1698 * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
1701 protected function prepareRequestUri()
1705 if ($this->headers->has('X_ORIGINAL_URL')) {
1706 // IIS with Microsoft Rewrite Module
1707 $requestUri = $this->headers->get('X_ORIGINAL_URL');
1708 $this->headers->remove('X_ORIGINAL_URL');
1709 $this->server->remove('HTTP_X_ORIGINAL_URL');
1710 $this->server->remove('UNENCODED_URL');
1711 $this->server->remove('IIS_WasUrlRewritten');
1712 } elseif ($this->headers->has('X_REWRITE_URL')) {
1713 // IIS with ISAPI_Rewrite
1714 $requestUri = $this->headers->get('X_REWRITE_URL');
1715 $this->headers->remove('X_REWRITE_URL');
1716 } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
1717 // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
1718 $requestUri = $this->server->get('UNENCODED_URL');
1719 $this->server->remove('UNENCODED_URL');
1720 $this->server->remove('IIS_WasUrlRewritten');
1721 } elseif ($this->server->has('REQUEST_URI')) {
1722 $requestUri = $this->server->get('REQUEST_URI');
1723 // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path
1724 $schemeAndHttpHost = $this->getSchemeAndHttpHost();
1725 if (strpos($requestUri, $schemeAndHttpHost) === 0) {
1726 $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
1728 } elseif ($this->server->has('ORIG_PATH_INFO')) {
1729 // IIS 5.0, PHP as CGI
1730 $requestUri = $this->server->get('ORIG_PATH_INFO');
1731 if ('' != $this->server->get('QUERY_STRING')) {
1732 $requestUri .= '?'.$this->server->get('QUERY_STRING');
1734 $this->server->remove('ORIG_PATH_INFO');
1737 // normalize the request URI to ease creating sub-requests from this request
1738 $this->server->set('REQUEST_URI', $requestUri);
1744 * Prepares the base URL.
1748 protected function prepareBaseUrl()
1750 $filename = basename($this->server->get('SCRIPT_FILENAME'));
1752 if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
1753 $baseUrl = $this->server->get('SCRIPT_NAME');
1754 } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
1755 $baseUrl = $this->server->get('PHP_SELF');
1756 } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
1757 $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
1759 // Backtrack up the script_filename to find the portion matching
1761 $path = $this->server->get('PHP_SELF', '');
1762 $file = $this->server->get('SCRIPT_FILENAME', '');
1763 $segs = explode('/', trim($file, '/'));
1764 $segs = array_reverse($segs);
1766 $last = count($segs);
1769 $seg = $segs[$index];
1770 $baseUrl = '/'.$seg.$baseUrl;
1772 } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
1775 // Does the baseUrl have anything in common with the request_uri?
1776 $requestUri = $this->getRequestUri();
1777 if ($requestUri !== '' && $requestUri[0] !== '/') {
1778 $requestUri = '/'.$requestUri;
1781 if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
1782 // full $baseUrl matches
1786 if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(dirname($baseUrl), '/'.DIRECTORY_SEPARATOR).'/')) {
1787 // directory portion of $baseUrl matches
1788 return rtrim($prefix, '/'.DIRECTORY_SEPARATOR);
1791 $truncatedRequestUri = $requestUri;
1792 if (false !== $pos = strpos($requestUri, '?')) {
1793 $truncatedRequestUri = substr($requestUri, 0, $pos);
1796 $basename = basename($baseUrl);
1797 if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
1798 // no match whatsoever; set it blank
1802 // If using mod_rewrite or ISAPI_Rewrite strip the script filename
1803 // out of baseUrl. $pos !== 0 makes sure it is not matching a value
1804 // from PATH_INFO or QUERY_STRING
1805 if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && $pos !== 0) {
1806 $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
1809 return rtrim($baseUrl, '/'.DIRECTORY_SEPARATOR);
1813 * Prepares the base path.
1815 * @return string base path
1817 protected function prepareBasePath()
1819 $filename = basename($this->server->get('SCRIPT_FILENAME'));
1820 $baseUrl = $this->getBaseUrl();
1821 if (empty($baseUrl)) {
1825 if (basename($baseUrl) === $filename) {
1826 $basePath = dirname($baseUrl);
1828 $basePath = $baseUrl;
1831 if ('\\' === DIRECTORY_SEPARATOR) {
1832 $basePath = str_replace('\\', '/', $basePath);
1835 return rtrim($basePath, '/');
1839 * Prepares the path info.
1841 * @return string path info
1843 protected function preparePathInfo()
1845 $baseUrl = $this->getBaseUrl();
1847 if (null === ($requestUri = $this->getRequestUri())) {
1851 // Remove the query string from REQUEST_URI
1852 if (false !== $pos = strpos($requestUri, '?')) {
1853 $requestUri = substr($requestUri, 0, $pos);
1855 if ($requestUri !== '' && $requestUri[0] !== '/') {
1856 $requestUri = '/'.$requestUri;
1859 $pathInfo = substr($requestUri, strlen($baseUrl));
1860 if (null !== $baseUrl && (false === $pathInfo || '' === $pathInfo)) {
1861 // If substr() returns false then PATH_INFO is set to an empty string
1863 } elseif (null === $baseUrl) {
1867 return (string) $pathInfo;
1871 * Initializes HTTP request formats.
1873 protected static function initializeFormats()
1875 static::$formats = array(
1876 'html' => array('text/html', 'application/xhtml+xml'),
1877 'txt' => array('text/plain'),
1878 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
1879 'css' => array('text/css'),
1880 'json' => array('application/json', 'application/x-json'),
1881 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
1882 'rdf' => array('application/rdf+xml'),
1883 'atom' => array('application/atom+xml'),
1884 'rss' => array('application/rss+xml'),
1885 'form' => array('application/x-www-form-urlencoded'),
1890 * Sets the default PHP locale.
1892 * @param string $locale
1894 private function setPhpDefaultLocale($locale)
1896 // if either the class Locale doesn't exist, or an exception is thrown when
1897 // setting the default locale, the intl module is not installed, and
1898 // the call can be ignored:
1900 if (class_exists('Locale', false)) {
1901 \Locale::setDefault($locale);
1903 } catch (\Exception $e) {
1908 * Returns the prefix as encoded in the string when the string starts with
1909 * the given prefix, false otherwise.
1911 * @param string $string The urlencoded string
1912 * @param string $prefix The prefix not encoded
1914 * @return string|false The prefix as it is encoded in $string, or false
1916 private function getUrlencodedPrefix($string, $prefix)
1918 if (0 !== strpos(rawurldecode($string), $prefix)) {
1922 $len = strlen($prefix);
1924 if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
1931 private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
1933 if (self::$requestFactory) {
1934 $request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
1936 if (!$request instanceof self) {
1937 throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
1943 return new static($query, $request, $attributes, $cookies, $files, $server, $content);
1947 * Indicates whether this request originated from a trusted proxy.
1949 * This can be useful to determine whether or not to trust the
1950 * contents of a proxy-specific header.
1952 * @return bool true if the request came from a trusted proxy, false otherwise
1954 public function isFromTrustedProxy()
1956 return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies);
1959 private function getTrustedValues($type, $ip = null)
1961 $clientValues = array();
1962 $forwardedValues = array();
1964 if (self::$trustedHeaders[$type] && $this->headers->has(self::$trustedHeaders[$type])) {
1965 foreach (explode(',', $this->headers->get(self::$trustedHeaders[$type])) as $v) {
1966 $clientValues[] = (self::HEADER_CLIENT_PORT === $type ? '0.0.0.0:' : '').trim($v);
1970 if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) {
1971 $forwardedValues = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]);
1972 $forwardedValues = preg_match_all(sprintf('{(?:%s)=(?:"?\[?)([a-zA-Z0-9\.:_\-/]*+)}', self::$forwardedParams[$type]), $forwardedValues, $matches) ? $matches[1] : array();
1976 $clientValues = $this->normalizeAndFilterClientIps($clientValues, $ip);
1977 $forwardedValues = $this->normalizeAndFilterClientIps($forwardedValues, $ip);
1980 if ($forwardedValues === $clientValues || !$clientValues) {
1981 return $forwardedValues;
1984 if (!$forwardedValues) {
1985 return $clientValues;
1988 if (!$this->isForwardedValid) {
1989 return null !== $ip ? array('0.0.0.0', $ip) : array();
1991 $this->isForwardedValid = false;
1993 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]));
1996 private function normalizeAndFilterClientIps(array $clientIps, $ip)
2001 $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
2002 $firstTrustedIp = null;
2004 foreach ($clientIps as $key => $clientIp) {
2005 // Remove port (unfortunately, it does happen)
2006 if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) {
2007 $clientIps[$key] = $clientIp = $match[1];
2010 if (!filter_var($clientIp, FILTER_VALIDATE_IP)) {
2011 unset($clientIps[$key]);
2016 if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
2017 unset($clientIps[$key]);
2019 // Fallback to this when the client IP falls into the range of trusted proxies
2020 if (null === $firstTrustedIp) {
2021 $firstTrustedIp = $clientIp;
2026 // Now the IP chain contains only untrusted proxies and the client IP
2027 return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp);