• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / http / 39952423518

23 Oct 2026 11:40AM UTC coverage: 83.32% (-1.3%) from 84.65%
39952423518

push

github

dg
added upgrading.md

1039 of 1247 relevant lines covered (83.32%)

0.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.08
/src/Http/RequestFactory.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Nette\Http;
9

10
use Nette;
11
use Nette\Utils\{Arrays, Strings};
12
use function function_exists, in_array, ini_get, is_array, is_string, sprintf, strlen;
13
use const PHP_SAPI;
14

15

16
/**
17
 * HTTP request factory.
18
 */
19
class RequestFactory
20
{
21
        /** @internal */
22
        private const ValidChars = '\x09\x0A\x0D\x20-\x7E\xA0-\x{10FFFF}';
23

24
        /**
25
         * Regex-based filters applied to the URL before parsing. 'path' filters run on the path component only;
26
         * 'url' filters run on the full request URI.
27
         * @var array<string, array<string, string>>
28
         */
29
        public array $urlFilters = [
30
                'path' => ['#//#' => '/'], // '%20' => ''
31
                'url' => [], // '#[.,)]$#D' => ''
32
        ];
33

34
        private bool $binary = false;
35
        private bool $forceHttps = false;
36
        private ?Url $baseUrl = null;
37

38
        /** @var list<string> */
39
        private array $proxies = [];
40

41
        private bool $forwarded = true;
42
        private bool $xForwarded = true;
43

44

45
        /**
46
         * Disables sanitization of request data (GET, POST, cookies, file names) for binary-safe handling.
47
         */
48
        public function setBinary(bool $binary = true): static
49
        {
50
                $this->binary = $binary;
1 ✔
51
                return $this;
1 ✔
52
        }
53

54

55
        /**
56
         * Sets the trusted proxy IP addresses or CIDR blocks used to resolve the real client IP and URL scheme,
57
         * and which forwarding headers to trust from them ("Forwarded" and/or "X-Forwarded-*").
58
         * @param string|list<string>  $proxy
59
         */
60
        public function setProxy(string|array $proxy, bool $forwarded = true, bool $xForwarded = true): static
61
        {
62
                $this->proxies = (array) $proxy;
1 ✔
63
                $this->forwarded = $forwarded;
1 ✔
64
                $this->xForwarded = $xForwarded;
1 ✔
65
                return $this;
1 ✔
66
        }
67

68

69
        /**
70
         * Forces the request scheme to HTTPS regardless of the server environment.
71
         */
72
        public function setForceHttps(bool $forceHttps = true): static
73
        {
74
                $this->forceHttps = $forceHttps;
1 ✔
75
                return $this;
1 ✔
76
        }
77

78

79
        /**
80
         * Sets the base URL of the application, used when it cannot be detected from the environment (CLI).
81
         */
82
        public function setBaseUrl(string|Url $url): static
83
        {
84
                $this->baseUrl = new Url($url);
1 ✔
85
                if ($this->baseUrl->getHost() === '') {
1 ✔
86
                        throw new Nette\InvalidArgumentException("Base URL '$url' must be absolute.");
1 ✔
87
                }
88

89
                $this->baseUrl->setPath(rtrim($this->baseUrl->getPath(), '/') . '/');
1 ✔
90
                return $this;
1 ✔
91
        }
92

93

94
        /**
95
         * Returns new Request instance, using values from superglobals.
96
         */
97
        public function fromGlobals(): Request
98
        {
99
                $url = new Url;
1 ✔
100
                $this->getServer($url);
1 ✔
101
                $this->getPathAndQuery($url);
1 ✔
102
                [$post, $cookies] = $this->getGetPostCookie($url);
1 ✔
103
                $remoteAddr = $this->getClient($url);
1 ✔
104
                if ($url->getHost() === '' && $this->baseUrl) {
1 ✔
105
                        $url->setScheme($this->baseUrl->getScheme())
1 ✔
106
                                ->setHost($this->baseUrl->getHost())
1 ✔
107
                                ->setPath($scriptPath = $this->baseUrl->getPath());
1 ✔
108
                        if (($port = $this->baseUrl->getPort()) && $port !== $this->baseUrl->getDefaultPort()) {
1 ✔
109
                                $url->setPort($port);
1 ✔
110
                        }
111
                } else {
112
                        $scriptPath = $this->getScriptPath($url);
1 ✔
113
                }
114

115
                if ($this->forceHttps) {
1 ✔
116
                        $url->setScheme('https');
1 ✔
117
                }
118

119
                return new Request(
1 ✔
120
                        new UrlScript($url, $scriptPath),
1 ✔
121
                        $post,
122
                        $this->getFiles(),
1 ✔
123
                        $cookies,
124
                        $this->getHeaders(),
1 ✔
125
                        $this->getMethod(),
1 ✔
126
                        $remoteAddr,
127
                        null,
1 ✔
128
                        fn() => (string) file_get_contents('php://input'),
1 ✔
129
                );
130
        }
131

132

133
        private function getServer(Url $url): void
134
        {
135
                $url->setScheme(!empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https' : 'http');
1 ✔
136

137
                if (
138
                        (isset($_SERVER[$tmp = 'HTTP_HOST']) || isset($_SERVER[$tmp = 'SERVER_NAME']))
1 ✔
139
                        && ($pair = $this->parseHostAndPort($_SERVER[$tmp]))
1 ✔
140
                ) {
141
                        $url->setHost($pair[0]);
1 ✔
142
                        if (isset($pair[1])) {
1 ✔
143
                                $url->setPort($pair[1]);
1 ✔
144
                        } elseif ($tmp === 'SERVER_NAME' && isset($_SERVER['SERVER_PORT'])) {
1 ✔
145
                                $url->setPort((int) $_SERVER['SERVER_PORT']);
1 ✔
146
                        }
147
                }
148
        }
1 ✔
149

150

151
        private function getPathAndQuery(Url $url): void
152
        {
153
                $requestUrl = $_SERVER['REQUEST_URI'] ?? '/';
1 ✔
154
                $requestUrl = preg_replace('#^\w++://[^/]++#', '', $requestUrl);
1 ✔
155
                $requestUrl = Strings::replace($requestUrl, $this->urlFilters['url']);
1 ✔
156

157
                $tmp = explode('?', $requestUrl, 2);
1 ✔
158
                $path = Url::unescape($tmp[0], '%/?#');
1 ✔
159
                $path = Strings::fixEncoding(Strings::replace($path, $this->urlFilters['path']));
1 ✔
160
                $url->setPath($path);
1 ✔
161
                $url->setQuery($tmp[1] ?? '');
1 ✔
162
        }
1 ✔
163

164

165
        private function getScriptPath(Url $url): string
166
        {
167
                if (PHP_SAPI === 'cli-server') {
1 ✔
168
                        return '/';
×
169
                }
170

171
                $path = $url->getPath();
1 ✔
172
                $lpath = strtolower($path);
1 ✔
173
                $script = strtolower($_SERVER['SCRIPT_NAME'] ?? '');
1 ✔
174
                if ($lpath !== $script) {
1 ✔
175
                        $max = min(strlen($lpath), strlen($script));
1 ✔
176
                        for ($i = 0; $i < $max && $lpath[$i] === $script[$i]; $i++);
1 ✔
177
                        $path = $i
1 ✔
178
                                ? substr($path, 0, strrpos($path, '/', $i - strlen($path) - 1) + 1)
1 ✔
179
                                : '/';
1 ✔
180
                }
181

182
                return $path;
1 ✔
183
        }
184

185

186
        /** @return array{mixed[], mixed[]} */
187
        private function getGetPostCookie(Url $url): array
188
        {
189
                $useFilter = (!in_array((string) ini_get('filter.default'), ['', 'unsafe_raw'], true) || ini_get('filter.default_flags'));
1 ✔
190

191
                $query = $url->getQueryParameters();
1 ✔
192
                $post = $useFilter
1 ✔
193
                        ? filter_input_array(INPUT_POST, FILTER_UNSAFE_RAW)
×
194
                        : (empty($_POST) ? [] : $_POST);
1 ✔
195
                $cookies = $useFilter
1 ✔
196
                        ? filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW)
×
197
                        : (empty($_COOKIE) ? [] : $_COOKIE);
1 ✔
198

199
                // remove invalid characters
200
                $reChars = '#^[' . self::ValidChars . ']*+$#Du';
1 ✔
201
                if (!$this->binary) {
1 ✔
202
                        $list = [&$query, &$post, &$cookies];
1 ✔
203
                        foreach ($list as $key => &$val) {
1 ✔
204
                                foreach ($val as $k => $v) {
1 ✔
205
                                        if (is_string($k) && (!preg_match($reChars, $k) || preg_last_error())) {
1 ✔
206
                                                unset($list[$key][$k]);
1 ✔
207

208
                                        } elseif (is_array($v)) {
1 ✔
209
                                                $list[$key][$k] = $v;
1 ✔
210
                                                $list[] = &$list[$key][$k];
1 ✔
211

212
                                        } elseif (is_string($v)) {
1 ✔
213
                                                $list[$key][$k] = (string) preg_replace('#[^' . self::ValidChars . ']+#u', '', $v);
1 ✔
214

215
                                        } else {
216
                                                throw new Nette\InvalidStateException(sprintf(
1 ✔
217
                                                        'Invalid value in $_POST/$_COOKIE in key %s, expected string, %s given.',
218
                                                        "'$k'",
1 ✔
219
                                                        get_debug_type($v),
1 ✔
220
                                                ));
221
                                        }
222
                                }
223
                        }
224

225
                        unset($list, $key, $val, $k, $v);
1 ✔
226
                }
227

228
                $url->setQuery($query);
1 ✔
229
                return [$post, $cookies];
1 ✔
230
        }
231

232

233
        /** @return mixed[] */
234
        private function getFiles(): array
235
        {
236
                $reChars = '#^[' . self::ValidChars . ']*+$#Du';
1 ✔
237
                $files = [];
1 ✔
238
                $list = [];
1 ✔
239
                foreach ($_FILES ?? [] as $k => $v) {
1 ✔
240
                        if (
241
                                !is_array($v)
1 ✔
242
                                || !isset($v['name'], $v['type'], $v['size'], $v['tmp_name'], $v['error'])
1 ✔
243
                                || (!$this->binary && is_string($k) && (!preg_match($reChars, $k) || preg_last_error()))
1 ✔
244
                        ) {
245
                                continue;
1 ✔
246
                        }
247

248
                        $v['@'] = &$files[$k];
1 ✔
249
                        $list[] = $v;
1 ✔
250
                }
251

252
                // create FileUpload objects
253
                foreach ($list as &$v) {
1 ✔
254
                        if (!isset($v['name'])) {
1 ✔
255
                                continue;
×
256

257
                        } elseif (!is_array($v['name'])) {
1 ✔
258
                                if (!$this->binary && (!preg_match($reChars, $v['name']) || preg_last_error())) {
1 ✔
259
                                        $v['name'] = '';
1 ✔
260
                                }
261

262
                                if ($v['error'] !== UPLOAD_ERR_NO_FILE) {
1 ✔
263
                                        $v['@'] = new FileUpload($v);
1 ✔
264
                                }
265

266
                                continue;
1 ✔
267
                        }
268

269
                        foreach ($v['name'] as $k => $foo) {
1 ✔
270
                                if (!$this->binary && is_string($k) && (!preg_match($reChars, $k) || preg_last_error())) {
1 ✔
271
                                        continue;
×
272
                                }
273

274
                                $list[] = [
1 ✔
275
                                        'name' => $v['name'][$k],
1 ✔
276
                                        'type' => $v['type'][$k],
1 ✔
277
                                        'size' => $v['size'][$k],
1 ✔
278
                                        'full_path' => $v['full_path'][$k] ?? null,
1 ✔
279
                                        'tmp_name' => $v['tmp_name'][$k],
1 ✔
280
                                        'error' => $v['error'][$k],
1 ✔
281
                                        '@' => &$v['@'][$k],
1 ✔
282
                                ];
283
                        }
284
                }
285

286
                return $files;
1 ✔
287
        }
288

289

290
        /** @return array<string, string> */
291
        private function getHeaders(): array
292
        {
293
                if (function_exists('apache_request_headers')) {
1 ✔
294
                        $headers = apache_request_headers() ?: [];
×
295
                } else {
296
                        $headers = [];
1 ✔
297
                        foreach ($_SERVER as $k => $v) {
1 ✔
298
                                if (str_starts_with($k, 'HTTP_')) {
1 ✔
299
                                        $k = substr($k, 5);
1 ✔
300
                                } elseif (strncmp($k, 'CONTENT_', 8)) {
1 ✔
301
                                        continue;
1 ✔
302
                                }
303

304
                                $headers[strtr($k, '_', '-')] = $v;
1 ✔
305
                        }
306
                }
307

308
                if (!isset($headers['Authorization'])) {
1 ✔
309
                        if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
1 ✔
310
                                $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);
1 ✔
311
                        } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
1 ✔
312
                                $headers['Authorization'] = 'Digest ' . $_SERVER['PHP_AUTH_DIGEST'];
1 ✔
313
                        }
314
                }
315

316
                return $headers;
1 ✔
317
        }
318

319

320
        private function getMethod(): string
321
        {
322
                $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
1 ✔
323
                if (
324
                        $method === 'POST'
1 ✔
325
                        && preg_match('#^[A-Z]+$#D', $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ?? '')
1 ✔
326
                ) {
327
                        $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
1 ✔
328
                }
329

330
                return $method;
1 ✔
331
        }
332

333

334
        private function getClient(Url $url): ?string
335
        {
336
                $remoteAddr = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
1 ✔
337

338
                // trust forwarding headers only when the request comes through a trusted proxy;
339
                // the proxy in turn should strip any forwarding header it does not set itself
340
                $client = $remoteAddr ? IPAddress::tryFrom($remoteAddr) : null;
1 ✔
341
                $usingTrustedProxy = $client && Arrays::some($this->proxies, fn(string $proxy): bool => $client->isInRange($proxy));
1 ✔
342
                if ($usingTrustedProxy) {
1 ✔
343
                        return match (true) {
344
                                $this->forwarded && !empty($_SERVER['HTTP_FORWARDED']) => $this->useForwardedProxy($url),
1 ✔
345
                                $this->xForwarded => $this->useNonstandardProxy($url),
1 ✔
346
                                default => $remoteAddr,
1 ✔
347
                        };
348
                }
349

350
                return $remoteAddr;
1 ✔
351
        }
352

353

354
        private function useForwardedProxy(Url $url): ?string
355
        {
356
                // RFC 7239: split into hops (comma), each a set of params (semicolon)
357
                $hops = $addresses = [];
1 ✔
358
                foreach (explode(',', $_SERVER['HTTP_FORWARDED']) as $element) {
1 ✔
359
                        $hop = [];
1 ✔
360
                        foreach (explode(';', $element) as $pair) {
1 ✔
361
                                [$key, $value] = explode('=', $pair, 2) + [1 => ''];
1 ✔
362
                                $hop[strtolower(trim($key))] = trim($value, " \t\"");
1 ✔
363
                        }
364

365
                        $for = $hop['for'] ?? '';
1 ✔
366
                        $addresses[] = str_contains($for, '[')
1 ✔
367
                                ? substr($for, 1, strpos($for, ']') - 1) // IPv6 "[addr]:port"
1 ✔
368
                                : explode(':', $for)[0]; // IPv4 "addr:port" or bare address
1 ✔
369
                        $hops[] = $hop;
1 ✔
370
                }
371

372
                $clientHop = $this->findClientHop($addresses);
1 ✔
373
                if ($clientHop === null) {
1 ✔
374
                        return null;
1 ✔
375
                }
376

377
                // scheme and host from the client's own hop
378
                $hop = $hops[$clientHop[0]];
1 ✔
379
                if (isset($hop['proto'])) {
1 ✔
380
                        $url->setScheme(strcasecmp($hop['proto'], 'https') === 0 ? 'https' : 'http');
1 ✔
381
                        $url->setPort($url->getScheme() === 'https' ? 443 : 80);
1 ✔
382
                }
383

384
                if (isset($hop['host']) && ($pair = $this->parseHostAndPort($hop['host']))) {
1 ✔
385
                        $url->setHost($pair[0]);
1 ✔
386
                        if (isset($pair[1])) {
1 ✔
387
                                $url->setPort($pair[1]);
1 ✔
388
                        }
389
                }
390

391
                return $clientHop[1];
1 ✔
392
        }
393

394

395
        private function useNonstandardProxy(Url $url): ?string
396
        {
397
                if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
1 ✔
398
                        $url->setScheme(strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0 ? 'https' : 'http');
1 ✔
399
                        $url->setPort($url->getScheme() === 'https' ? 443 : 80);
1 ✔
400
                }
401

402
                if (!empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
1 ✔
403
                        $url->setPort((int) $_SERVER['HTTP_X_FORWARDED_PORT']);
1 ✔
404
                }
405

406
                if (empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1 ✔
407
                        return null;
1 ✔
408
                }
409

410
                $clientHop = $this->findClientHop(array_map(trim(...), explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
1 ✔
411
                if ($clientHop === null) {
1 ✔
412
                        return null;
1 ✔
413
                }
414

415
                if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
1 ✔
416
                        $hosts = explode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
1 ✔
417
                        if (isset($hosts[$clientHop[0]]) && ($pair = $this->parseHostAndPort(trim($hosts[$clientHop[0]])))) {
1 ✔
418
                                $url->setHost($pair[0]);
1 ✔
419
                                if (isset($pair[1])) {
1 ✔
420
                                        $url->setPort($pair[1]);
1 ✔
421
                                }
422
                        }
423
                }
424

425
                return $clientHop[1];
1 ✔
426
        }
427

428

429
        /**
430
         * Returns [index, address] of the rightmost hop after stripping trailing trusted proxies,
431
         * or null when that hop is not a valid IP.
432
         * @param  list<string>  $addresses
433
         * @return array{int, string}|null
434
         */
435
        private function findClientHop(array $addresses): ?array
436
        {
437
                $untrusted = array_filter(
1 ✔
438
                        $addresses,
439
                        fn(string $ip): bool => ($address = IPAddress::tryFrom($ip)) === null
1 ✔
440
                                || !Arrays::some($this->proxies, fn(string $proxy): bool => $address->isInRange($proxy)),
1 ✔
441
                );
442
                if (!$untrusted) {
1 ✔
443
                        return null;
×
444
                }
445

446
                $index = array_key_last($untrusted);
1 ✔
447
                return IPAddress::tryFrom($untrusted[$index]) === null
1 ✔
448
                        ? null
1 ✔
449
                        : [$index, $untrusted[$index]];
1 ✔
450
        }
451

452

453
        /** @return array{string, ?int}|null */
454
        private function parseHostAndPort(string $s): ?array
455
        {
456
                return preg_match('#^([a-z0-9_.-]+|\[[a-f0-9:]+])(:\d+)?$#Di', $s, $matches)
1 ✔
457
                        ? [
458
                                rtrim(strtolower($matches[1]), '.'),
1 ✔
459
                                isset($matches[2]) ? (int) substr($matches[2], 1) : null,
1 ✔
460
                        ]
461
                        : null;
1 ✔
462
        }
463

464

465
        /** @deprecated */
466
        public function createHttpRequest(): Request
467
        {
468
                return $this->fromGlobals();
×
469
        }
470
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc