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

nette / http / 26458288420

26 May 2026 03:31PM UTC coverage: 84.24% (+0.7%) from 83.513%
26458288420

push

github

dg
added Request::isFrom() WIP

11 of 11 new or added lines in 1 file covered. (100.0%)

32 existing lines in 4 files now uncovered.

1053 of 1250 relevant lines covered (84.24%)

0.84 hits per line

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

96.76
/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, base64_encode, count, end, explode, file_get_contents, filter_input_array, filter_var, function_exists, get_debug_type, in_array, ini_get, is_array, is_string, key, min, preg_last_error, preg_match, preg_replace, preg_split, 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

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

40
        private bool $forceHttps = false;
41

42

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

52

53
        /**
54
         * Sets the trusted proxy IP addresses or CIDR blocks used to resolve the real client IP and URL scheme.
55
         * @param string|list<string>  $proxy
56
         */
57
        public function setProxy($proxy): static
58
        {
59
                $this->proxies = (array) $proxy;
1✔
60
                return $this;
1✔
61
        }
62

63

64
        /**
65
         * Forces the request scheme to HTTPS regardless of the server environment.
66
         */
67
        public function setForceHttps(bool $forceHttps = true): static
1✔
68
        {
69
                $this->forceHttps = $forceHttps;
1✔
70
                return $this;
1✔
71
        }
72

73

74
        /**
75
         * Returns new Request instance, using values from superglobals.
76
         */
77
        public function fromGlobals(): Request
78
        {
79
                $url = new Url;
1✔
80
                $this->getServer($url);
1✔
81
                $this->getPathAndQuery($url);
1✔
82
                [$post, $cookies] = $this->getGetPostCookie($url);
1✔
83
                [$remoteAddr, $remoteHost] = $this->getClient($url);
1✔
84

85
                if ($this->forceHttps) {
1✔
86
                        $url->setScheme('https');
1✔
87
                }
88

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

102

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

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

120

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

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

134

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

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

152
                return $path;
1✔
153
        }
154

155

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

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

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

178
                                        } elseif (is_array($v)) {
1✔
179
                                                $list[$key][$k] = $v;
1✔
180
                                                $list[] = &$list[$key][$k];
1✔
181

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

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

191
                        unset($list, $key, $val, $k, $v);
1✔
192
                }
193

194
                $url->setQuery($query);
1✔
195
                return [$post, $cookies];
1✔
196
        }
197

198

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

214
                        $v['@'] = &$files[$k];
1✔
215
                        $list[] = $v;
1✔
216
                }
217

218
                // create FileUpload objects
219
                foreach ($list as &$v) {
1✔
220
                        if (!is_array($v['name'])) {
1✔
221
                                if (!$this->binary && (!preg_match($reChars, $v['name']) || preg_last_error())) {
1✔
222
                                        $v['name'] = '';
1✔
223
                                }
224

225
                                if ($v['error'] !== UPLOAD_ERR_NO_FILE) {
1✔
226
                                        $v['@'] = new FileUpload($v);
1✔
227
                                }
228

229
                                continue;
1✔
230
                        }
231

232
                        foreach ($v['name'] as $k => $foo) {
1✔
233
                                if (!$this->binary && is_string($k) && (!preg_match($reChars, $k) || preg_last_error())) {
1✔
UNCOV
234
                                        continue;
×
235
                                }
236

237
                                $list[] = [
1✔
238
                                        'name' => $v['name'][$k],
1✔
239
                                        'type' => $v['type'][$k],
1✔
240
                                        'size' => $v['size'][$k],
1✔
241
                                        'full_path' => $v['full_path'][$k] ?? null,
1✔
242
                                        'tmp_name' => $v['tmp_name'][$k],
1✔
243
                                        'error' => $v['error'][$k],
1✔
244
                                        '@' => &$v['@'][$k],
1✔
245
                                ];
246
                        }
247
                }
248

249
                return $files;
1✔
250
        }
251

252

253
        /** @return array<string, string> */
254
        private function getHeaders(): array
255
        {
256
                if (function_exists('apache_request_headers')) {
1✔
UNCOV
257
                        $headers = apache_request_headers();
×
258
                } else {
259
                        $headers = [];
1✔
260
                        foreach ($_SERVER as $k => $v) {
1✔
261
                                if (str_starts_with($k, 'HTTP_')) {
1✔
262
                                        $k = substr($k, 5);
1✔
263
                                } elseif (strncmp($k, 'CONTENT_', 8)) {
1✔
264
                                        continue;
1✔
265
                                }
266

267
                                $headers[strtr($k, '_', '-')] = $v;
1✔
268
                        }
269
                }
270

271
                if (!isset($headers['Authorization'])) {
1✔
272
                        if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
1✔
273
                                $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);
1✔
274
                        } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
1✔
275
                                $headers['Authorization'] = 'Digest ' . $_SERVER['PHP_AUTH_DIGEST'];
1✔
276
                        }
277
                }
278

279
                return $headers;
1✔
280
        }
281

282

283
        private function getMethod(): string
284
        {
285
                $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
1✔
286
                if (
287
                        $method === 'POST'
1✔
288
                        && preg_match('#^[A-Z]+$#D', $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ?? '')
1✔
289
                ) {
290
                        $method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
1✔
291
                }
292

293
                return $method;
1✔
294
        }
295

296

297
        /** @return array{?string, ?string}  [remoteAddr, remoteHost] */
298
        private function getClient(Url $url): array
1✔
299
        {
300
                $remoteAddr = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
1✔
301

302
                // use real client address and host if trusted proxy is used
303
                $usingTrustedProxy = $remoteAddr && Arrays::some($this->proxies, fn(string $proxy): bool => Helpers::ipMatch($remoteAddr, $proxy));
1✔
304
                if ($usingTrustedProxy) {
1✔
305
                        $remoteHost = null;
1✔
306
                        $remoteAddr = empty($_SERVER['HTTP_FORWARDED'])
1✔
307
                                ? $this->useNonstandardProxy($url)
1✔
308
                                : $this->useForwardedProxy($url);
1✔
309

310
                } else {
311
                        $remoteHost = !empty($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : null;
1✔
312
                }
313

314
                return [$remoteAddr, $remoteHost];
1✔
315
        }
316

317

318
        private function useForwardedProxy(Url $url): ?string
1✔
319
        {
320
                $forwardParams = preg_split('/[,;]/', $_SERVER['HTTP_FORWARDED']);
1✔
321
                foreach ($forwardParams as $forwardParam) {
1✔
322
                        [$key, $value] = explode('=', $forwardParam, 2) + [1 => ''];
1✔
323
                        $proxyParams[strtolower(trim($key))][] = trim($value, " \t\"");
1✔
324
                }
325

326
                if (isset($proxyParams['for'])) {
1✔
327
                        $address = $proxyParams['for'][0];
1✔
328
                        $remoteAddr = str_contains($address, '[')
1✔
329
                                ? substr($address, 1, strpos($address, ']') - 1) // IPv6
1✔
330
                                : explode(':', $address)[0];  // IPv4
1✔
331
                }
332

333
                if (isset($proxyParams['proto']) && count($proxyParams['proto']) === 1) {
1✔
334
                        $url->setScheme(strcasecmp($proxyParams['proto'][0], 'https') === 0 ? 'https' : 'http');
1✔
335
                        $url->setPort($url->getScheme() === 'https' ? 443 : 80);
1✔
336
                }
337

338
                if (
339
                        isset($proxyParams['host']) && count($proxyParams['host']) === 1
1✔
340
                        && ($pair = $this->parseHostAndPort($proxyParams['host'][0]))
1✔
341
                ) {
342
                        $url->setHost($pair[0]);
1✔
343
                        if (isset($pair[1])) {
1✔
344
                                $url->setPort($pair[1]);
1✔
345
                        }
346
                }
347
                return $remoteAddr ?? null;
1✔
348
        }
349

350

351
        private function useNonstandardProxy(Url $url): ?string
1✔
352
        {
353
                if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
1✔
354
                        $url->setScheme(strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0 ? 'https' : 'http');
1✔
355
                        $url->setPort($url->getScheme() === 'https' ? 443 : 80);
1✔
356
                }
357

358
                if (!empty($_SERVER['HTTP_X_FORWARDED_PORT'])) {
1✔
359
                        $url->setPort((int) $_SERVER['HTTP_X_FORWARDED_PORT']);
1✔
360
                }
361

362
                if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1✔
363
                        $xForwardedForWithoutProxies = array_filter(
1✔
364
                                explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']),
1✔
365
                                fn(string $ip): bool => filter_var($ip = trim($ip), FILTER_VALIDATE_IP) === false
1✔
366
                                        || !Arrays::some($this->proxies, fn(string $proxy): bool => Helpers::ipMatch($ip, $proxy)),
1✔
367
                        );
368
                        if ($xForwardedForWithoutProxies) {
1✔
369
                                $remoteAddr = trim(end($xForwardedForWithoutProxies));
1✔
370
                                $xForwardedForRealIpKey = key($xForwardedForWithoutProxies);
1✔
371
                        }
372
                }
373

374
                if (isset($xForwardedForRealIpKey) && !empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
1✔
375
                        $xForwardedHost = explode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
1✔
376
                        if (
377
                                isset($xForwardedHost[$xForwardedForRealIpKey])
1✔
378
                                && ($pair = $this->parseHostAndPort(trim($xForwardedHost[$xForwardedForRealIpKey])))
1✔
379
                        ) {
380
                                $url->setHost($pair[0]);
1✔
381
                                if (isset($pair[1])) {
1✔
382
                                        $url->setPort($pair[1]);
1✔
383
                                }
384
                        }
385
                }
386

387
                return $remoteAddr ?? null;
1✔
388
        }
389

390

391
        /** @return array{string, ?int}|null */
392
        private function parseHostAndPort(string $s): ?array
1✔
393
        {
394
                return preg_match('#^([a-z0-9_.-]+|\[[a-f0-9:]+])(:\d+)?$#Di', $s, $matches)
1✔
395
                        ? [
396
                                rtrim(strtolower($matches[1]), '.'),
1✔
397
                                isset($matches[2]) ? (int) substr($matches[2], 1) : null,
1✔
398
                        ]
399
                        : null;
1✔
400
        }
401

402

403
        /** @deprecated */
404
        public function createHttpRequest(): Request
405
        {
UNCOV
406
                return $this->fromGlobals();
×
407
        }
408
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc