0

Sometimes I need to use a value that is dynamic in a way that it would be different depending on whether the code is executed on a testing environment or a remote host.

To address that I've been using the following function:

function localhost($local_host_value, $remote_host_value = "")
{
   if($_SERVER["REMOTE_ADDR"] == "127.0.0.1")
   {
      return $local_host_value;
   }
   else
   {
      return $remote_host_value;
   }
}

Could you suggest a more elegant approach or at least a better name for the above quoted function?

Emanuil Rusev
  • 34,563
  • 55
  • 137
  • 201

3 Answers3

1

you can try getenv('REMOTE_ADDR'); if you dis-like using super-global variables

// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];

as for the function name

function is_localhost(...)    <-- more like determine is local host (boolean)

function get_host_value(...)  <-- (string)
ajreal
  • 46,720
  • 11
  • 89
  • 119
  • 2
    `is_localhost(...)` for me suggests that it will return a boolean wether we are in localhost or not... I find `get_value_for_host(...)` or `get_host_value(...)` more descriptive – maid450 Dec 30 '10 at 13:09
1
function localhost($local_host_value, $remote_host_value = '') {
    return $_SERVER['REMOTE_ADDR'] == '127.0.0.1'? $local_host_value : $remote_host_value;
}

Is more concise and clean in my opinion, but does just the same. Or with getenv as ajreal suggests:

function localhost($local_host_value, $remote_host_value = '') {
    return getenv('REMOTE_ADDR') == '127.0.0.1'? $local_host_value : $remote_host_value;
}

About the function name, maybe get_host_value(...) would be my choice

PS: try to use single quotes instead of double quotes when your string does not contain variables: Is there a performance benefit single quote vs double quote in php?

Community
  • 1
  • 1
maid450
  • 7,478
  • 3
  • 37
  • 32
1

I think this approach is not optimal in the long run, as all the settings are distributed all over your code, and it's very hard to e.g. add a third server environment (say, a live staging server).

I would consider using a central configuration of some sort that loads all configuration values at one point depending on which server it is running on.

Related:

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088