I know this seem to be trivial and maybe it is, but I'm wondering about what's the best way to determine, whether a script is executed on localhost or not.
So far, I've used the following distinction when I had to execute different logic, depending on whether a script is being executed locally or not:
if ( $_SERVER['REMOTE_ADDR'] === '127.0.0.1' || $_SERVER['REMOTE_ADDR'] === '::1' ) {
// localhost-only stuff here (like different routing etc)
}
When I used this the very first time, I've checked obvious possibilities like:
- 127.0.0.1/foo.php
- 127.0.0.1:80/foo.php
- http://127.0.0.1/foo.php
- http://127.0.0.1:80/foo.php
- https://127.0.0.1/foo.php
- https://127.0.0.1:443/foo.php
- localhost/foo.php
- localhost:80/foo.php
- http://localhost/foo.php
- http://localhost:80/foo.php
- https://localhost/foo.php
- https://localhost:443/foo.php
Since the statement worked fine for all those variants, I didn't really care anymore about this. In meantime I've noticed that this does not really cover all cases, for example, when using the host name itself like in
- http://mycomputer/foo.php
because $_SERVER['REMOTE_ADDR'] won't contains the loopback but local link ip (like fe80:... etc). This leads me to the question if there's a simple/safe/fast solution which really covers ALL possible ways for accessing localhost, since I'm sure there are plenty other variantions which could occur.
// Edit: There is no need to get the client ip as long as the script may take another execution path if running on localhost than if running on the webhost. For example to apply different document root paths without using vhosts or things like that
// Edit2: For now, it seems like there is no better solution than checking all possibly remote addresses like in the following:
if ( $_SERVER['REMOTE_ADDR'] === '127.0.0.1' ||
$_SERVER['REMOTE_ADDR'] === '::1' ||
str_starts_with($_SERVER['REMOTE_ADDR'], 'fe80:') ||
str_starts_with($_SERVER['REMOTE_ADDR'], '169.254.') ) {
// running on localhost
}