I'm wondering how I can detect if the user is on a localhost.
My reason for doing so is so that I can automatically run production code on a live server, but uncompressed code on my machine, without having to change the link all the time.
I know I can do it in JS like this... if(document.URL.indexOf("localhost:8888") <= 0){
But I need to do it in Php for my WordPress installation. I've come across a similar question here - How can I detect if the user is on localhost in PHP?
So I tried this (below), but it fails to load anything
<?php if(IPAddress::In(array("127.0.0.1","::1"))) { ?>
<script src="<?php bloginfo('template_url'); ?>/js/scripts.js"></script>
<?php } ?>
I've also tried the suggested solution here, but again, doesn't work for me How can I detect if the user is on localhost in PHP?
In case these details help, I'm using MAMP on Mac, with a WordPress installation.
Use the $_SERVER global vars: http://www.php.net/manual/en/reserved.variables.server.php
if (in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) {
// code for localhost here
}
EDIT: Regarding TerryE's comment, you may want to do something like this (or see his regex answer, although it may not be needed):
if (substr($_SERVER['REMOTE_ADDR'], 0, 4) == '127.'
|| $_SERVER['REMOTE_ADDR'] == '::1') {
// code for localhost here
}
Because the localhost can be anything in 127.0.0.0/8, although 127.0.0.1 is the most common. http://en.wikipedia.org/wiki/Localhost
Although my original answer will probably be fine (it is what Symfony2 uses by default to "protect" the app_dev.php from accidental production use)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With