title: bulletproof determination of localhost
body: <p>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.</p>
  <p>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:</p>
  <pre><code>if ( $_SERVER['REMOTE_ADDR'] === '127.0.0.1' || $_SERVER['REMOTE_ADDR'] === '::1' ) {
    // localhost-only stuff here (like different routing etc)
  }
  </code></pre>
  <p>When I used this the very first time, I've checked obvious possibilities like:</p>
  <ul>
  <li>127.0.0.1/foo.php</li>
  <li>127.0.0.1:80/foo.php</li>
  <li><a href="http://127.0.0.1/foo.php" rel="nofollow noreferrer">http://127.0.0.1/foo.php</a></li>
  <li><a href="http://127.0.0.1:80/foo.php" rel="nofollow noreferrer">http://127.0.0.1:80/foo.php</a></li>
  <li><a href="https://127.0.0.1/foo.php" rel="nofollow noreferrer">https://127.0.0.1/foo.php</a></li>
  <li><a href="https://127.0.0.1:443/foo.php" rel="nofollow noreferrer">https://127.0.0.1:443/foo.php</a></li>
  <li>localhost/foo.php</li>
  <li>localhost:80/foo.php</li>
  <li>http://localhost/foo.php</li>
  <li>http://localhost:80/foo.php</li>
  <li>https://localhost/foo.php</li>
  <li>https://localhost:443/foo.php</li>
  </ul>
  <p>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</p>
  <ul>
  <li>http://mycomputer/foo.php</li>
  </ul>
  <p>because <em>$_SERVER['REMOTE_ADDR']</em> 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.</p>
  <p>// 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</p>
  <p>// Edit2: For now, it seems like there is no better solution than checking all possibly remote addresses like in the following:</p>
  <pre><code>    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
      }
  </code></pre>