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

nette / http / 39956161725

23 Oct 2026 12:45PM UTC coverage: 82.117% (-1.4%) from 83.509%
39956161725

push

github

dg
uses #Deprecated wip

1024 of 1247 relevant lines covered (82.12%)

0.82 hits per line

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

95.59
/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
                        fn() => (string) file_get_contents('php://input'),
1 ✔
128
                );
129
        }
130

131

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

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

149

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

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

163

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

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

181
                return $path;
1 ✔
182
        }
183

184

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

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

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

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

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

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

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

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

231

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

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

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

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

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

265
                                continue;
1 ✔
266
                        }
267

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

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

285
                return $files;
1 ✔
286
        }
287

288

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

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

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

315
                return $headers;
1 ✔
316
        }
317

318

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

329
                return $method;
1 ✔
330
        }
331

332

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

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

349
                return $remoteAddr;
1 ✔
350
        }
351

352

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

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

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

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

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

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

393

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

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

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

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

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

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

427

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

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

451

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

463

464
        #[\Deprecated('use fromGlobals()')]
465
        public function createHttpRequest(): Request
466
        {
467
                trigger_error(__METHOD__ . '() is deprecated, use fromGlobals()', E_USER_DEPRECATED);
×
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