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

nette / http / 29305157373

14 Jul 2026 04:06AM UTC coverage: 83.115% (+0.2%) from 82.955%
29305157373

push

github

dg
uses #Deprecated wip

1078 of 1297 relevant lines covered (83.11%)

0.83 hits per line

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

95.54
/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;
12
use Nette\Utils\Strings;
13
use function array_filter, array_key_last, array_map, base64_encode, explode, file_get_contents, filter_input_array, function_exists, get_debug_type, in_array, ini_get, is_array, is_string, min, preg_last_error, preg_match, preg_replace, rtrim, sprintf, str_contains, strcasecmp, strlen, strncmp, strpos, strrpos, strtolower, strtr, substr, trim;
14
use const PHP_SAPI;
15

16

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

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

35
        private bool $binary = false;
36
        private bool $forceHttps = false;
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
1✔
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
1✔
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
1✔
73
        {
74
                $this->forceHttps = $forceHttps;
1✔
75
                return $this;
1✔
76
        }
77

78

79
        /**
80
         * Returns new Request instance, using values from superglobals.
81
         */
82
        public function fromGlobals(): Request
83
        {
84
                $url = new Url;
1✔
85
                $this->getServer($url);
1✔
86
                $this->getPathAndQuery($url);
1✔
87
                [$post, $cookies] = $this->getGetPostCookie($url);
1✔
88
                $remoteAddr = $this->getClient($url);
1✔
89
                if ($this->forceHttps) {
1✔
90
                        $url->setScheme('https');
1✔
91
                }
92

93
                return new Request(
1✔
94
                        new UrlScript($url, $this->getScriptPath($url)),
1✔
95
                        $post,
96
                        $this->getFiles(),
1✔
97
                        $cookies,
98
                        $this->getHeaders(),
1✔
99
                        $this->getMethod(),
1✔
100
                        $remoteAddr,
101
                        fn() => (string) file_get_contents('php://input'),
1✔
102
                );
103
        }
104

105

106
        private function getServer(Url $url): void
1✔
107
        {
108
                $url->setScheme(!empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https' : 'http');
1✔
109

110
                if (
111
                        (isset($_SERVER[$tmp = 'HTTP_HOST']) || isset($_SERVER[$tmp = 'SERVER_NAME']))
1✔
112
                        && ($pair = $this->parseHostAndPort($_SERVER[$tmp]))
1✔
113
                ) {
114
                        $url->setHost($pair[0]);
1✔
115
                        if (isset($pair[1])) {
1✔
116
                                $url->setPort($pair[1]);
1✔
117
                        } elseif ($tmp === 'SERVER_NAME' && isset($_SERVER['SERVER_PORT'])) {
1✔
118
                                $url->setPort((int) $_SERVER['SERVER_PORT']);
1✔
119
                        }
120
                }
121
        }
1✔
122

123

124
        private function getPathAndQuery(Url $url): void
1✔
125
        {
126
                $requestUrl = $_SERVER['REQUEST_URI'] ?? '/';
1✔
127
                $requestUrl = preg_replace('#^\w++://[^/]++#', '', $requestUrl);
1✔
128
                $requestUrl = Strings::replace($requestUrl, $this->urlFilters['url']);
1✔
129

130
                $tmp = explode('?', $requestUrl, 2);
1✔
131
                $path = Url::unescape($tmp[0], '%/?#');
1✔
132
                $path = Strings::fixEncoding(Strings::replace($path, $this->urlFilters['path']));
1✔
133
                $url->setPath($path);
1✔
134
                $url->setQuery($tmp[1] ?? '');
1✔
135
        }
1✔
136

137

138
        private function getScriptPath(Url $url): string
1✔
139
        {
140
                if (PHP_SAPI === 'cli-server') {
1✔
141
                        return '/';
×
142
                }
143

144
                $path = $url->getPath();
1✔
145
                $lpath = strtolower($path);
1✔
146
                $script = strtolower($_SERVER['SCRIPT_NAME'] ?? '');
1✔
147
                if ($lpath !== $script) {
1✔
148
                        $max = min(strlen($lpath), strlen($script));
1✔
149
                        for ($i = 0; $i < $max && $lpath[$i] === $script[$i]; $i++);
1✔
150
                        $path = $i
1✔
151
                                ? substr($path, 0, strrpos($path, '/', $i - strlen($path) - 1) + 1)
1✔
152
                                : '/';
1✔
153
                }
154

155
                return $path;
1✔
156
        }
157

158

159
        /** @return array{mixed[], mixed[]} */
160
        private function getGetPostCookie(Url $url): array
1✔
161
        {
162
                $useFilter = (!in_array((string) ini_get('filter.default'), ['', 'unsafe_raw'], strict: true) || ini_get('filter.default_flags'));
1✔
163

164
                $query = $url->getQueryParameters();
1✔
165
                $post = $useFilter
1✔
166
                        ? filter_input_array(INPUT_POST, FILTER_UNSAFE_RAW)
×
167
                        : (empty($_POST) ? [] : $_POST);
1✔
168
                $cookies = $useFilter
1✔
169
                        ? filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW)
×
170
                        : (empty($_COOKIE) ? [] : $_COOKIE);
1✔
171

172
                // remove invalid characters
173
                $reChars = '#^[' . self::ValidChars . ']*+$#Du';
1✔
174
                if (!$this->binary) {
1✔
175
                        $list = [&$query, &$post, &$cookies];
1✔
176
                        foreach ($list as $key => &$val) {
1✔
177
                                foreach ($val as $k => $v) {
1✔
178
                                        if (is_string($k) && (!preg_match($reChars, $k) || preg_last_error())) {
1✔
179
                                                unset($list[$key][$k]);
1✔
180

181
                                        } elseif (is_array($v)) {
1✔
182
                                                $list[$key][$k] = $v;
1✔
183
                                                $list[] = &$list[$key][$k];
1✔
184

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

188
                                        } else {
189
                                                throw new Nette\InvalidStateException(sprintf('Invalid value in $_POST/$_COOKIE in key %s, expected string, %s given.', "'$k'", get_debug_type($v)));
1✔
190
                                        }
191
                                }
192
                        }
193

194
                        unset($list, $key, $val, $k, $v);
1✔
195
                }
196

197
                $url->setQuery($query);
1✔
198
                return [$post, $cookies];
1✔
199
        }
200

201

202
        /** @return mixed[] */
203
        private function getFiles(): array
204
        {
205
                $reChars = '#^[' . self::ValidChars . ']*+$#Du';
1✔
206
                $files = [];
1✔
207
                $list = [];
1✔
208
                foreach ($_FILES ?? [] as $k => $v) {
1✔
209
                        if (
210
                                !is_array($v)
1✔
211
                                || !isset($v['name'], $v['type'], $v['size'], $v['tmp_name'], $v['error'])
1✔
212
                                || (!$this->binary && is_string($k) && (!preg_match($reChars, $k) || preg_last_error()))
1✔
213
                        ) {
214
                                continue;
1✔
215
                        }
216

217
                        $v['@'] = &$files[$k];
1✔
218
                        $list[] = $v;
1✔
219
                }
220

221
                // create FileUpload objects
222
                foreach ($list as &$v) {
1✔
223
                        if (!isset($v['name'])) {
1✔
224
                                continue;
×
225

226
                        } elseif (!is_array($v['name'])) {
1✔
227
                                if (!$this->binary && (!preg_match($reChars, $v['name']) || preg_last_error())) {
1✔
228
                                        $v['name'] = '';
1✔
229
                                }
230

231
                                if ($v['error'] !== UPLOAD_ERR_NO_FILE) {
1✔
232
                                        $v['@'] = new FileUpload($v);
1✔
233
                                }
234

235
                                continue;
1✔
236
                        }
237

238
                        foreach ($v['name'] as $k => $foo) {
1✔
239
                                if (!$this->binary && is_string($k) && (!preg_match($reChars, $k) || preg_last_error())) {
1✔
240
                                        continue;
×
241
                                }
242

243
                                $list[] = [
1✔
244
                                        'name' => $v['name'][$k],
1✔
245
                                        'type' => $v['type'][$k],
1✔
246
                                        'size' => $v['size'][$k],
1✔
247
                                        'full_path' => $v['full_path'][$k] ?? null,
1✔
248
                                        'tmp_name' => $v['tmp_name'][$k],
1✔
249
                                        'error' => $v['error'][$k],
1✔
250
                                        '@' => &$v['@'][$k],
1✔
251
                                ];
252
                        }
253
                }
254

255
                return $files;
1✔
256
        }
257

258

259
        /** @return array<string, string> */
260
        private function getHeaders(): array
261
        {
262
                if (function_exists('apache_request_headers')) {
1✔
263
                        $headers = apache_request_headers() ?: [];
×
264
                } else {
265
                        $headers = [];
1✔
266
                        foreach ($_SERVER as $k => $v) {
1✔
267
                                if (str_starts_with($k, 'HTTP_')) {
1✔
268
                                        $k = substr($k, 5);
1✔
269
                                } elseif (strncmp($k, 'CONTENT_', 8)) {
1✔
270
                                        continue;
1✔
271
                                }
272

273
                                $headers[strtr($k, '_', '-')] = $v;
1✔
274
                        }
275
                }
276

277
                if (!isset($headers['Authorization'])) {
1✔
278
                        if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
1✔
279
                                $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);
1✔
280
                        } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
1✔
281
                                $headers['Authorization'] = 'Digest ' . $_SERVER['PHP_AUTH_DIGEST'];
1✔
282
                        }
283
                }
284

285
                return $headers;
1✔
286
        }
287

288

289
        private function getMethod(): string
290
        {
291
                $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
1✔
292
                if (
293
                        $method === 'POST'
1✔
294
                        && preg_match('#^[A-Z]+$#D', $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ?? '')
1✔
295
                ) {
296
                        $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
1✔
297
                }
298

299
                return $method;
1✔
300
        }
301

302

303
        private function getClient(Url $url): ?string
1✔
304
        {
305
                $remoteAddr = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
1✔
306

307
                // trust forwarding headers only when the request comes through a trusted proxy;
308
                // the proxy in turn should strip any forwarding header it does not set itself
309
                $client = $remoteAddr ? IPAddress::tryFrom($remoteAddr) : null;
1✔
310
                $usingTrustedProxy = $client && Arrays::some($this->proxies, fn(string $proxy): bool => $client->isInRange($proxy));
1✔
311
                if ($usingTrustedProxy) {
1✔
312
                        return match (true) {
313
                                $this->forwarded && !empty($_SERVER['HTTP_FORWARDED']) => $this->useForwardedProxy($url),
1✔
314
                                $this->xForwarded => $this->useNonstandardProxy($url),
1✔
315
                                default => $remoteAddr,
1✔
316
                        };
317
                }
318

319
                return $remoteAddr;
1✔
320
        }
321

322

323
        private function useForwardedProxy(Url $url): ?string
1✔
324
        {
325
                // RFC 7239: split into hops (comma), each a set of params (semicolon)
326
                $hops = $addresses = [];
1✔
327
                foreach (explode(',', $_SERVER['HTTP_FORWARDED']) as $element) {
1✔
328
                        $hop = [];
1✔
329
                        foreach (explode(';', $element) as $pair) {
1✔
330
                                [$key, $value] = explode('=', $pair, 2) + [1 => ''];
1✔
331
                                $hop[strtolower(trim($key))] = trim($value, " \t\"");
1✔
332
                        }
333

334
                        $for = $hop['for'] ?? '';
1✔
335
                        $addresses[] = str_contains($for, '[')
1✔
336
                                ? substr($for, 1, strpos($for, ']') - 1) // IPv6 "[addr]:port"
1✔
337
                                : explode(':', $for)[0]; // IPv4 "addr:port" or bare address
1✔
338
                        $hops[] = $hop;
1✔
339
                }
340

341
                $clientHop = $this->findClientHop($addresses);
1✔
342
                if ($clientHop === null) {
1✔
343
                        return null;
1✔
344
                }
345

346
                // scheme and host from the client's own hop
347
                $hop = $hops[$clientHop[0]];
1✔
348
                if (isset($hop['proto'])) {
1✔
349
                        $url->setScheme(strcasecmp($hop['proto'], 'https') === 0 ? 'https' : 'http');
1✔
350
                        $url->setPort($url->getScheme() === 'https' ? 443 : 80);
1✔
351
                }
352

353
                if (isset($hop['host']) && ($pair = $this->parseHostAndPort($hop['host']))) {
1✔
354
                        $url->setHost($pair[0]);
1✔
355
                        if (isset($pair[1])) {
1✔
356
                                $url->setPort($pair[1]);
1✔
357
                        }
358
                }
359

360
                return $clientHop[1];
1✔
361
        }
362

363

364
        private function useNonstandardProxy(Url $url): ?string
1✔
365
        {
366
                if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
1✔
367
                        $url->setScheme(strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0 ? 'https' : 'http');
1✔
368
                        $url->setPort($url->getScheme() === 'https' ? 443 : 80);
1✔
369
                }
370

371
                if (!empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
1✔
372
                        $url->setPort((int) $_SERVER['HTTP_X_FORWARDED_PORT']);
1✔
373
                }
374

375
                if (empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1✔
376
                        return null;
1✔
377
                }
378

379
                $clientHop = $this->findClientHop(array_map(trim(...), explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
1✔
380
                if ($clientHop === null) {
1✔
381
                        return null;
1✔
382
                }
383

384
                if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
1✔
385
                        $hosts = explode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
1✔
386
                        if (isset($hosts[$clientHop[0]]) && ($pair = $this->parseHostAndPort(trim($hosts[$clientHop[0]])))) {
1✔
387
                                $url->setHost($pair[0]);
1✔
388
                                if (isset($pair[1])) {
1✔
389
                                        $url->setPort($pair[1]);
1✔
390
                                }
391
                        }
392
                }
393

394
                return $clientHop[1];
1✔
395
        }
396

397

398
        /**
399
         * Returns [index, address] of the rightmost hop after stripping trailing trusted proxies,
400
         * or null when that hop is not a valid IP.
401
         * @param  list<string>  $addresses
402
         * @return array{int, string}|null
403
         */
404
        private function findClientHop(array $addresses): ?array
1✔
405
        {
406
                $untrusted = array_filter(
1✔
407
                        $addresses,
1✔
408
                        fn(string $ip): bool => ($address = IPAddress::tryFrom($ip)) === null
1✔
409
                                || !Arrays::some($this->proxies, fn(string $proxy): bool => $address->isInRange($proxy)),
1✔
410
                );
411
                if (!$untrusted) {
1✔
412
                        return null;
×
413
                }
414

415
                $index = array_key_last($untrusted);
1✔
416
                return IPAddress::tryFrom($untrusted[$index]) === null
1✔
417
                        ? null
1✔
418
                        : [$index, $untrusted[$index]];
1✔
419
        }
420

421

422
        /** @return array{string, ?int}|null */
423
        private function parseHostAndPort(string $s): ?array
1✔
424
        {
425
                return preg_match('#^([a-z0-9_.-]+|\[[a-f0-9:]+])(:\d+)?$#Di', $s, $matches)
1✔
426
                        ? [
427
                                rtrim(strtolower($matches[1]), '.'),
1✔
428
                                isset($matches[2]) ? (int) substr($matches[2], 1) : null,
1✔
429
                        ]
430
                        : null;
1✔
431
        }
432

433

434
        #[\Deprecated('use fromGlobals()')]
435
        public function createHttpRequest(): Request
436
        {
437
                trigger_error(__METHOD__ . '() is deprecated, use fromGlobals()', E_USER_DEPRECATED);
×
438
                return $this->fromGlobals();
×
439
        }
440
}
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