Auto detect internal/external development environment

后端 未结 5 622
清歌不尽
清歌不尽 2021-02-04 14:04

We use the following function to auto detect if we are on a machine internally or on a live server and then choose the appropriate configs for various components:



        
相关标签:
5条回答
  • 2021-02-04 14:32

    Create and later look for a file that only exists on the live server's filesystem.

    Granted, your environments should be as similar as possible; what I'm suggesting is something like this: in directory /var/environment/, have a file named {devel|test|qa|staging|live}, depending on the server you're on - then just check the filename.

    Of course, you need to exclude this file from version control and from whatever build process you may have.

    0 讨论(0)
  • 2021-02-04 14:33

    Set an environment variable in your Apache virtual host configuration. This is the way the Zend Framework does it.

    See the ZF quick start guide for an example (the "Create a Virtual Host" section.)

    In your httpd.conf or a .htaccess file, put:

    SetEnv APPLICATION_ENV "development"
    

    Then in your application, use the getenv function to get the value:

    $environment = getenv("APPLICATION_ENV");
    if ($environment == "development")
    {
        // do development stuff
    }
    else if ($environment == "live")
    {
        // do live stuff
    }
    
    0 讨论(0)
  • 2021-02-04 14:36
    '127.0.0.1' == $_SERVER["REMOTE_ADDR"]
    

    This will never evaluate as TRUE on your live system. :)

    0 讨论(0)
  • 2021-02-04 14:42

    Of course, if you have use virtual host locally like example.com then the function will be tricked.

    Also if the host is not local but uses a widlcard or default vhost defn and the user adds the IP address to the hosts file locally.

    I would recommend having a directory on the include path which also exists on live but is not replicated there - and simply store:

    function getEnv(){
      return 'Live';
    }
    

    or

    function getEnv(){
      return 'Test';
    }
    

    If both envs are on the same server - you can still do this by setting the include_path in Apache config or .htaccess.

    This also allows you to seperate potentially sensitive env specific data - like database hosts/passwords and encyption keys.

    C.

    0 讨论(0)
  • 2021-02-04 14:47

    Adding to Andy Shellam's answer..

    If you are using mod_vhost_alias, or have various domains with the same (virtual) document root, you can set the variable dependent upon parameters, e.g.

    SetEnvIf SERVER_ADDR x.x.x.x APPLICATION_ENV=development
    SetEnvIf HTTP_HOST abc.example.com APPLICATION_ENV=development
    
    0 讨论(0)
提交回复
热议问题