-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Request.php
2105 lines (1816 loc) · 69.2 KB
/
Request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;
use Symfony\Component\HttpFoundation\Exception\JsonException;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
// Help opcache.preload discover always-needed symbols
class_exists(AcceptHeader::class);
class_exists(FileBag::class);
class_exists(HeaderBag::class);
class_exists(HeaderUtils::class);
class_exists(InputBag::class);
class_exists(ParameterBag::class);
class_exists(ServerBag::class);
/**
* Request represents an HTTP request.
*
* The methods dealing with URL accept / return a raw path (% encoded):
* * getBasePath
* * getBaseUrl
* * getPathInfo
* * getRequestUri
* * getUri
* * getUriForPath
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Request
{
public const HEADER_FORWARDED = 0b000001; // When using RFC 7239
public const HEADER_X_FORWARDED_FOR = 0b000010;
public const HEADER_X_FORWARDED_HOST = 0b000100;
public const HEADER_X_FORWARDED_PROTO = 0b001000;
public const HEADER_X_FORWARDED_PORT = 0b010000;
public const HEADER_X_FORWARDED_PREFIX = 0b100000;
public const HEADER_X_FORWARDED_AWS_ELB = 0b0011010; // AWS ELB doesn't send X-Forwarded-Host
public const HEADER_X_FORWARDED_TRAEFIK = 0b0111110; // All "X-Forwarded-*" headers sent by Traefik reverse proxy
public const METHOD_HEAD = 'HEAD';
public const METHOD_GET = 'GET';
public const METHOD_POST = 'POST';
public const METHOD_PUT = 'PUT';
public const METHOD_PATCH = 'PATCH';
public const METHOD_DELETE = 'DELETE';
public const METHOD_PURGE = 'PURGE';
public const METHOD_OPTIONS = 'OPTIONS';
public const METHOD_TRACE = 'TRACE';
public const METHOD_CONNECT = 'CONNECT';
/**
* @var string[]
*/
protected static array $trustedProxies = [];
/**
* @var string[]
*/
protected static array $trustedHostPatterns = [];
/**
* @var string[]
*/
protected static array $trustedHosts = [];
protected static bool $httpMethodParameterOverride = false;
/**
* Custom parameters.
*/
public ParameterBag $attributes;
/**
* Request body parameters ($_POST).
*
* @see getPayload() for portability between content types
*/
public InputBag $request;
/**
* Query string parameters ($_GET).
*/
public InputBag $query;
/**
* Server and execution environment parameters ($_SERVER).
*/
public ServerBag $server;
/**
* Uploaded files ($_FILES).
*/
public FileBag $files;
/**
* Cookies ($_COOKIE).
*/
public InputBag $cookies;
/**
* Headers (taken from the $_SERVER).
*/
public HeaderBag $headers;
/**
* @var string|resource|false|null
*/
protected $content;
/**
* @var string[]|null
*/
protected ?array $languages = null;
/**
* @var string[]|null
*/
protected ?array $charsets = null;
/**
* @var string[]|null
*/
protected ?array $encodings = null;
/**
* @var string[]|null
*/
protected ?array $acceptableContentTypes = null;
protected ?string $pathInfo = null;
protected ?string $requestUri = null;
protected ?string $baseUrl = null;
protected ?string $basePath = null;
protected ?string $method = null;
protected ?string $format = null;
protected SessionInterface|\Closure|null $session = null;
protected ?string $locale = null;
protected string $defaultLocale = 'en';
/**
* @var array<string, string[]>|null
*/
protected static ?array $formats = null;
protected static ?\Closure $requestFactory = null;
private ?string $preferredFormat = null;
private bool $isHostValid = true;
private bool $isForwardedValid = true;
private bool $isSafeContentPreferred;
private array $trustedValuesCache = [];
private static int $trustedHeaderSet = -1;
private const FORWARDED_PARAMS = [
self::HEADER_X_FORWARDED_FOR => 'for',
self::HEADER_X_FORWARDED_HOST => 'host',
self::HEADER_X_FORWARDED_PROTO => 'proto',
self::HEADER_X_FORWARDED_PORT => 'host',
];
/**
* Names for headers that can be trusted when
* using trusted proxies.
*
* The FORWARDED header is the standard as of rfc7239.
*
* The other headers are non-standard, but widely used
* by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
*/
private const TRUSTED_HEADERS = [
self::HEADER_FORWARDED => 'FORWARDED',
self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
self::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
self::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
self::HEADER_X_FORWARDED_PREFIX => 'X_FORWARDED_PREFIX',
];
/** @var bool */
private $isIisRewrite = false;
/**
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
* @param string|resource|null $content The raw body data
*/
public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null)
{
$this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}
/**
* Sets the parameters for this request.
*
* This method also re-initializes all properties.
*
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
* @param string|resource|null $content The raw body data
*/
public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): void
{
$this->request = new InputBag($request);
$this->query = new InputBag($query);
$this->attributes = new ParameterBag($attributes);
$this->cookies = new InputBag($cookies);
$this->files = new FileBag($files);
$this->server = new ServerBag($server);
$this->headers = new HeaderBag($this->server->getHeaders());
$this->content = $content;
$this->languages = null;
$this->charsets = null;
$this->encodings = null;
$this->acceptableContentTypes = null;
$this->pathInfo = null;
$this->requestUri = null;
$this->baseUrl = null;
$this->basePath = null;
$this->method = null;
$this->format = null;
}
/**
* Creates a new request with values from PHP's super globals.
*/
public static function createFromGlobals(): static
{
$request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER);
if (str_starts_with($request->headers->get('CONTENT_TYPE', ''), 'application/x-www-form-urlencoded')
&& \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), ['PUT', 'DELETE', 'PATCH'], true)
) {
parse_str($request->getContent(), $data);
$request->request = new InputBag($data);
}
return $request;
}
/**
* Creates a Request based on a given URI and configuration.
*
* The information contained in the URI always take precedence
* over the other information (server and parameters).
*
* @param string $uri The URI
* @param string $method The HTTP method
* @param array $parameters The query (GET) or request (POST) parameters
* @param array $cookies The request cookies ($_COOKIE)
* @param array $files The request files ($_FILES)
* @param array $server The server parameters ($_SERVER)
* @param string|resource|null $content The raw body data
*
* @throws BadRequestException When the URI is invalid
*/
public static function create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content = null): static
{
$server = array_replace([
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => 80,
'HTTP_HOST' => 'localhost',
'HTTP_USER_AGENT' => 'Symfony',
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'REMOTE_ADDR' => '127.0.0.1',
'SCRIPT_NAME' => '',
'SCRIPT_FILENAME' => '',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_TIME' => time(),
'REQUEST_TIME_FLOAT' => microtime(true),
], $server);
$server['PATH_INFO'] = '';
$server['REQUEST_METHOD'] = strtoupper($method);
if (false === $components = parse_url(\strlen($uri) !== strcspn($uri, '?#') ? $uri : $uri.'#')) {
throw new BadRequestException('Invalid URI.');
}
if (false !== ($i = strpos($uri, '\\')) && $i < strcspn($uri, '?#')) {
throw new BadRequestException('Invalid URI: A URI cannot contain a backslash.');
}
if (\strlen($uri) !== strcspn($uri, "\r\n\t")) {
throw new BadRequestException('Invalid URI: A URI cannot contain CR/LF/TAB characters.');
}
if ('' !== $uri && (\ord($uri[0]) <= 32 || \ord($uri[-1]) <= 32)) {
throw new BadRequestException('Invalid URI: A URI must not start nor end with ASCII control characters or spaces.');
}
if (isset($components['host'])) {
$server['SERVER_NAME'] = $components['host'];
$server['HTTP_HOST'] = $components['host'];
}
if (isset($components['scheme'])) {
if ('https' === $components['scheme']) {
$server['HTTPS'] = 'on';
$server['SERVER_PORT'] = 443;
} else {
unset($server['HTTPS']);
$server['SERVER_PORT'] = 80;
}
}
if (isset($components['port'])) {
$server['SERVER_PORT'] = $components['port'];
$server['HTTP_HOST'] .= ':'.$components['port'];
}
if (isset($components['user'])) {
$server['PHP_AUTH_USER'] = $components['user'];
}
if (isset($components['pass'])) {
$server['PHP_AUTH_PW'] = $components['pass'];
}
if (!isset($components['path'])) {
$components['path'] = '/';
}
switch (strtoupper($method)) {
case 'POST':
case 'PUT':
case 'DELETE':
if (!isset($server['CONTENT_TYPE'])) {
$server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
}
// no break
case 'PATCH':
$request = $parameters;
$query = [];
break;
default:
$request = [];
$query = $parameters;
break;
}
$queryString = '';
if (isset($components['query'])) {
parse_str(html_entity_decode($components['query']), $qs);
if ($query) {
$query = array_replace($qs, $query);
$queryString = http_build_query($query, '', '&');
} else {
$query = $qs;
$queryString = $components['query'];
}
} elseif ($query) {
$queryString = http_build_query($query, '', '&');
}
$server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : '');
$server['QUERY_STRING'] = $queryString;
return self::createRequestFromFactory($query, $request, [], $cookies, $files, $server, $content);
}
/**
* Sets a callable able to create a Request instance.
*
* This is mainly useful when you need to override the Request class
* to keep BC with an existing system. It should not be used for any
* other purpose.
*/
public static function setFactory(?callable $callable): void
{
self::$requestFactory = null === $callable ? null : $callable(...);
}
/**
* Clones a request and overrides some of its parameters.
*
* @param array|null $query The GET parameters
* @param array|null $request The POST parameters
* @param array|null $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array|null $cookies The COOKIE parameters
* @param array|null $files The FILES parameters
* @param array|null $server The SERVER parameters
*/
public function duplicate(?array $query = null, ?array $request = null, ?array $attributes = null, ?array $cookies = null, ?array $files = null, ?array $server = null): static
{
$dup = clone $this;
if (null !== $query) {
$dup->query = new InputBag($query);
}
if (null !== $request) {
$dup->request = new InputBag($request);
}
if (null !== $attributes) {
$dup->attributes = new ParameterBag($attributes);
}
if (null !== $cookies) {
$dup->cookies = new InputBag($cookies);
}
if (null !== $files) {
$dup->files = new FileBag($files);
}
if (null !== $server) {
$dup->server = new ServerBag($server);
$dup->headers = new HeaderBag($dup->server->getHeaders());
}
$dup->languages = null;
$dup->charsets = null;
$dup->encodings = null;
$dup->acceptableContentTypes = null;
$dup->pathInfo = null;
$dup->requestUri = null;
$dup->baseUrl = null;
$dup->basePath = null;
$dup->method = null;
$dup->format = null;
if (!$dup->get('_format') && $this->get('_format')) {
$dup->attributes->set('_format', $this->get('_format'));
}
if (!$dup->getRequestFormat(null)) {
$dup->setRequestFormat($this->getRequestFormat(null));
}
return $dup;
}
/**
* Clones the current request.
*
* Note that the session is not cloned as duplicated requests
* are most of the time sub-requests of the main one.
*/
public function __clone()
{
$this->query = clone $this->query;
$this->request = clone $this->request;
$this->attributes = clone $this->attributes;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
public function __toString(): string
{
$content = $this->getContent();
$cookieHeader = '';
$cookies = [];
foreach ($this->cookies as $k => $v) {
$cookies[] = \is_array($v) ? http_build_query([$k => $v], '', '; ', \PHP_QUERY_RFC3986) : "$k=$v";
}
if ($cookies) {
$cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
}
return
sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
$this->headers.
$cookieHeader."\r\n".
$content;
}
/**
* Overrides the PHP global variables according to this request instance.
*
* It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE.
* $_FILES is never overridden, see rfc1867
*/
public function overrideGlobals(): void
{
$this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '', '&')));
$_GET = $this->query->all();
$_POST = $this->request->all();
$_SERVER = $this->server->all();
$_COOKIE = $this->cookies->all();
foreach ($this->headers->all() as $key => $value) {
$key = strtoupper(str_replace('-', '_', $key));
if (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH', 'CONTENT_MD5'], true)) {
$_SERVER[$key] = implode(', ', $value);
} else {
$_SERVER['HTTP_'.$key] = implode(', ', $value);
}
}
$request = ['g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE];
$requestOrder = \ini_get('request_order') ?: \ini_get('variables_order');
$requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp';
$_REQUEST = [[]];
foreach (str_split($requestOrder) as $order) {
$_REQUEST[] = $request[$order];
}
$_REQUEST = array_merge(...$_REQUEST);
}
/**
* Sets a list of trusted proxies.
*
* You should only list the reverse proxies that you manage directly.
*
* @param array $proxies A list of trusted proxies, the string 'REMOTE_ADDR' will be replaced with $_SERVER['REMOTE_ADDR']
* @param int $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies
*/
public static function setTrustedProxies(array $proxies, int $trustedHeaderSet): void
{
self::$trustedProxies = array_reduce($proxies, function ($proxies, $proxy) {
if ('REMOTE_ADDR' !== $proxy) {
$proxies[] = $proxy;
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$proxies[] = $_SERVER['REMOTE_ADDR'];
}
return $proxies;
}, []);
self::$trustedHeaderSet = $trustedHeaderSet;
}
/**
* Gets the list of trusted proxies.
*
* @return string[]
*/
public static function getTrustedProxies(): array
{
return self::$trustedProxies;
}
/**
* Gets the set of trusted headers from trusted proxies.
*
* @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies
*/
public static function getTrustedHeaderSet(): int
{
return self::$trustedHeaderSet;
}
/**
* Sets a list of trusted host patterns.
*
* You should only list the hosts you manage using regexs.
*
* @param array $hostPatterns A list of trusted host patterns
*/
public static function setTrustedHosts(array $hostPatterns): void
{
self::$trustedHostPatterns = array_map(fn ($hostPattern) => sprintf('{%s}i', $hostPattern), $hostPatterns);
// we need to reset trusted hosts on trusted host patterns change
self::$trustedHosts = [];
}
/**
* Gets the list of trusted host patterns.
*
* @return string[]
*/
public static function getTrustedHosts(): array
{
return self::$trustedHostPatterns;
}
/**
* Normalizes a query string.
*
* It builds a normalized query string, where keys/value pairs are alphabetized,
* have consistent escaping and unneeded delimiters are removed.
*/
public static function normalizeQueryString(?string $qs): string
{
if ('' === ($qs ?? '')) {
return '';
}
$qs = HeaderUtils::parseQuery($qs);
ksort($qs);
return http_build_query($qs, '', '&', \PHP_QUERY_RFC3986);
}
/**
* Enables support for the _method request parameter to determine the intended HTTP method.
*
* Be warned that enabling this feature might lead to CSRF issues in your code.
* Check that you are using CSRF tokens when required.
* If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered
* and used to send a "PUT" or "DELETE" request via the _method request parameter.
* If these methods are not protected against CSRF, this presents a possible vulnerability.
*
* The HTTP method can only be overridden when the real HTTP method is POST.
*/
public static function enableHttpMethodParameterOverride(): void
{
self::$httpMethodParameterOverride = true;
}
/**
* Checks whether support for the _method request parameter is enabled.
*/
public static function getHttpMethodParameterOverride(): bool
{
return self::$httpMethodParameterOverride;
}
/**
* Gets a "parameter" value from any bag.
*
* This method is mainly useful for libraries that want to provide some flexibility. If you don't need the
* flexibility in controllers, it is better to explicitly get request parameters from the appropriate
* public property instead (attributes, query, request).
*
* Order of precedence: PATH (routing placeholders or custom attributes), GET, POST
*
* @internal use explicit input sources instead
*/
public function get(string $key, mixed $default = null): mixed
{
if ($this !== $result = $this->attributes->get($key, $this)) {
return $result;
}
if ($this->query->has($key)) {
return $this->query->all()[$key];
}
if ($this->request->has($key)) {
return $this->request->all()[$key];
}
return $default;
}
/**
* Gets the Session.
*
* @throws SessionNotFoundException When session is not set properly
*/
public function getSession(): SessionInterface
{
$session = $this->session;
if (!$session instanceof SessionInterface && null !== $session) {
$this->setSession($session = $session());
}
if (null === $session) {
throw new SessionNotFoundException('Session has not been set.');
}
return $session;
}
/**
* Whether the request contains a Session which was started in one of the
* previous requests.
*/
public function hasPreviousSession(): bool
{
// the check for $this->session avoids malicious users trying to fake a session cookie with proper name
return $this->hasSession() && $this->cookies->has($this->getSession()->getName());
}
/**
* Whether the request contains a Session object.
*
* This method does not give any information about the state of the session object,
* like whether the session is started or not. It is just a way to check if this Request
* is associated with a Session instance.
*
* @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory`
*/
public function hasSession(bool $skipIfUninitialized = false): bool
{
return null !== $this->session && (!$skipIfUninitialized || $this->session instanceof SessionInterface);
}
public function setSession(SessionInterface $session): void
{
$this->session = $session;
}
/**
* @internal
*
* @param callable(): SessionInterface $factory
*/
public function setSessionFactory(callable $factory): void
{
$this->session = $factory(...);
}
/**
* Returns the client IP addresses.
*
* In the returned array the most trusted IP address is first, and the
* least trusted one last. The "real" client IP address is the last one,
* but this is also the least trusted one. Trusted proxies are stripped.
*
* Use this method carefully; you should use getClientIp() instead.
*
* @see getClientIp()
*/
public function getClientIps(): array
{
$ip = $this->server->get('REMOTE_ADDR');
if (!$this->isFromTrustedProxy()) {
return [$ip];
}
return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR, $ip) ?: [$ip];
}
/**
* Returns the client IP address.
*
* This method can read the client IP address from the "X-Forwarded-For" header
* when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
* header value is a comma+space separated list of IP addresses, the left-most
* being the original client, and each successive proxy that passed the request
* adding the IP address where it received the request from.
*
* If your reverse proxy uses a different header name than "X-Forwarded-For",
* ("Client-Ip" for instance), configure it via the $trustedHeaderSet
* argument of the Request::setTrustedProxies() method instead.
*
* @see getClientIps()
* @see https://wikipedia.org/wiki/X-Forwarded-For
*/
public function getClientIp(): ?string
{
$ipAddresses = $this->getClientIps();
return $ipAddresses[0];
}
/**
* Returns current script name.
*/
public function getScriptName(): string
{
return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
}
/**
* Returns the path being requested relative to the executed script.
*
* The path info always starts with a /.
*
* Suppose this request is instantiated from /mysite on localhost:
*
* * http://localhost/mysite returns an empty string
* * http://localhost/mysite/about returns '/about'
* * http://localhost/mysite/enco%20ded returns '/enco%20ded'
* * http://localhost/mysite/about?var=1 returns '/about'
*
* @return string The raw path (i.e. not urldecoded)
*/
public function getPathInfo(): string
{
return $this->pathInfo ??= $this->preparePathInfo();
}
/**
* Returns the root path from which this request is executed.
*
* Suppose that an index.php file instantiates this request object:
*
* * http://localhost/index.php returns an empty string
* * http://localhost/index.php/page returns an empty string
* * http://localhost/web/index.php returns '/web'
* * http://localhost/we%20b/index.php returns '/we%20b'
*
* @return string The raw path (i.e. not urldecoded)
*/
public function getBasePath(): string
{
return $this->basePath ??= $this->prepareBasePath();
}
/**
* Returns the root URL from which this request is executed.
*
* The base URL never ends with a /.
*
* This is similar to getBasePath(), except that it also includes the
* script filename (e.g. index.php) if one exists.
*
* @return string The raw URL (i.e. not urldecoded)
*/
public function getBaseUrl(): string
{
$trustedPrefix = '';
// the proxy prefix must be prepended to any prefix being needed at the webserver level
if ($this->isFromTrustedProxy() && $trustedPrefixValues = $this->getTrustedValues(self::HEADER_X_FORWARDED_PREFIX)) {
$trustedPrefix = rtrim($trustedPrefixValues[0], '/');
}
return $trustedPrefix.$this->getBaseUrlReal();
}
/**
* Returns the real base URL received by the webserver from which this request is executed.
* The URL does not include trusted reverse proxy prefix.
*
* @return string The raw URL (i.e. not urldecoded)
*/
private function getBaseUrlReal(): string
{
return $this->baseUrl ??= $this->prepareBaseUrl();
}
/**
* Gets the request's scheme.
*/
public function getScheme(): string
{
return $this->isSecure() ? 'https' : 'http';
}
/**
* Returns the port on which the request is made.
*
* This method can read the client port from the "X-Forwarded-Port" header
* when trusted proxies were set via "setTrustedProxies()".
*
* The "X-Forwarded-Port" header must contain the client port.
*
* @return int|string|null Can be a string if fetched from the server bag
*/
public function getPort(): int|string|null
{
if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_PORT)) {
$host = $host[0];
} elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) {
$host = $host[0];
} elseif (!$host = $this->headers->get('HOST')) {
return $this->server->get('SERVER_PORT');
}
if ('[' === $host[0]) {
$pos = strpos($host, ':', strrpos($host, ']'));
} else {
$pos = strrpos($host, ':');
}
if (false !== $pos && $port = substr($host, $pos + 1)) {
return (int) $port;
}
return 'https' === $this->getScheme() ? 443 : 80;
}
/**
* Returns the user.
*/
public function getUser(): ?string
{
return $this->headers->get('PHP_AUTH_USER');
}
/**
* Returns the password.
*/
public function getPassword(): ?string
{
return $this->headers->get('PHP_AUTH_PW');
}
/**
* Gets the user info.
*
* @return string|null A user name if any and, optionally, scheme-specific information about how to gain authorization to access the server
*/
public function getUserInfo(): ?string
{
$userinfo = $this->getUser();
$pass = $this->getPassword();
if ('' != $pass) {
$userinfo .= ":$pass";
}
return $userinfo;
}
/**
* Returns the HTTP host being requested.
*
* The port name will be appended to the host if it's non-standard.
*/
public function getHttpHost(): string
{
$scheme = $this->getScheme();
$port = $this->getPort();
if (('http' === $scheme && 80 == $port) || ('https' === $scheme && 443 == $port)) {
return $this->getHost();
}
return $this->getHost().':'.$port;
}
/**
* Returns the requested URI (path and query string).
*
* @return string The raw URI (i.e. not URI decoded)
*/
public function getRequestUri(): string
{
return $this->requestUri ??= $this->prepareRequestUri();
}
/**
* Gets the scheme and HTTP host.
*
* If the URL was called with basic authentication, the user
* and the password are not added to the generated string.
*/
public function getSchemeAndHttpHost(): string
{
return $this->getScheme().'://'.$this->getHttpHost();
}
/**
* Generates a normalized URI (URL) for the Request.
*
* @see getQueryString()
*/
public function getUri(): string
{
if (null !== $qs = $this->getQueryString()) {
$qs = '?'.$qs;
}
return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
}
/**
* Generates a normalized URI for the given path.
*
* @param string $path A path to use instead of the current one
*/
public function getUriForPath(string $path): string
{
return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
}
/**
* Returns the path as relative reference from the current Request path.
*
* Only the URIs path component (no schema, host etc.) is relevant and must be given.
* Both paths must be absolute and not contain relative parts.
* Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
* Furthermore, they can be used to reduce the link size in documents.
*
* Example target paths, given a base path of "/a/b/c/d":
* - "/a/b/c/d" -> ""
* - "/a/b/c/" -> "./"
* - "/a/b/" -> "../"
* - "/a/b/c/other" -> "other"
* - "/a/x/y" -> "../../x/y"
*/
public function getRelativeUriForPath(string $path): string
{