Core\Request::clientIp
Core\Request::clientIp(): ?tainted stringReturns the network address of the client that sent the request, as a string such as 203.0.113.7 or 2001:db8::1. An IPv6 address is always in its short form.
Your server may run behind a proxy or a load balancer. Then the address comes from the X-Forwarded-For header, but only when that proxy is listed in [server] trusted_proxies. Otherwise Novis ignores the header and gives the address of the connection itself. This way a client cannot choose its own address.
The result is null when the request has no address, for example over a Unix socket. The result is tainted, which means it came from outside your program. A command-line program answers no request, so clientIp throws a LogicError there.
Return value
Returns ?tainted string. The address as a tainted string, such as 203.0.113.7 or 2001:db8::1. An IPv6 address is always in its short form. The result is null when the request has no address, for example over a Unix socket.
Errors
LogicErrorThe program is not handling a request. For example, it is a command-line program, a job or a test.
Examples
Logging where a request came from
<?nvs// Shows how to write the address of the client into a log line.
// `Core\Request::clientIp` returns the address as a string, or `null`.// `??` replaces `null` with the text "unknown".tainted string $address = Core\Request::clientIp() ?? 'unknown';
// This prints "GET /orders from 203.0.113.7".echo 'GET /orders from ', $address, "\n";GET /orders from 203.0.113.7A request with no address
<?nvs// Shows what `Core\Request::clientIp` returns when the request has no address.// This happens, for example, when the request arrives over a Unix socket.
?tainted string $address = Core\Request::clientIp();
// The result is `null`. It is never an empty string.if ($address == null) { echo "the request has no address\n";} else { echo 'the request came from ', $address, "\n";}the request has no addressAn admin page for the office only
<?nvs// Shows how an admin page accepts only requests from the addresses of the office.
array<string> $office = ['203.0.113.8', '2001:db8::1'];
// The request came from 2001:0db8:0000::0001. `clientIp` returns the short form.// With no address, `??` gives the empty string, which is not in the list.tainted string $address = Core\Request::clientIp() ?? '';
// This loop checks the address against each address of the office.bool $allowed = false;foreach ($office as string $known) { if ($address == $known) { $allowed = true; }}
// This prints "admin page for 2001:db8::1".if ($allowed) { echo 'admin page for ', $address, "\n";} else { echo "403 Forbidden\n";}admin page for 2001:db8::1