Identify development vs. production server in PHP

后端 未结 5 775
Happy的楠姐
Happy的楠姐 2020-12-08 15:20

I work with two application servers on a daily basis: one development, one production. A variety of apps from different developers live on these boxes, as well as some scrip

相关标签:
5条回答
  • 2020-12-08 15:25

    A company I worked for previously used a convention of suffixing servers as follows:

    • L = Live
    • D = Dev
    • T = Test
    • U = UAT

    This makes determining the environment that you're working on, both inside and outside of Apache, fairly trivial.

    0 讨论(0)
  • 2020-12-08 15:27

    This came to my mind

    if(filter_var(ini_get('display_errors'), FILTER_VALIDATE_BOOLEAN))
    {
        // development
    } 
    else {
        // production
    }
    

    or a better approach

    define('IN_DEVELOPEMENT', filter_var(ini_get('display_errors'), FILTER_VALIDATE_BOOLEAN));
    
    0 讨论(0)
  • 2020-12-08 15:29

    use an environment variable

    Just set an environment variable. It works on Windows and linux, they are even called the same thing now. Then just check $_ENV["DEVVSPROD"]

    0 讨论(0)
  • 2020-12-08 15:36

    I ended up using $_ENV['HOSTNAME'], with php_uname("n") as a backup:

    /**  
     * Returns true if we are working on a development server, determined by server's
     * hostname. Will generate an error if run on an unknown host.
     */
    public static function isdev()
    {
      static $isdev = null;
    
      // don't run function body more than once
      if( null !== $isdev ) {
        return $isdev;
      }    
    
      // prefer HOSTNAME in the environment, which will be set in Apache.
      // use `uname -n' as a backup.
      if( isset( $_ENV['HOSTNAME'] ) ) {
        $hostname = $_ENV['HOSTNAME'];
      } else {
        $hostname = php_uname("n");
      }    
    
      switch( $hostname ) {
        case 'production1.example.com':
        case 'production2.example.com':
        case 'production3.example.com': $isdev = false; break;
    
        case 'dev1.example.com':
        case 'dev2':
        case 'dev2.example.com': $isdev = true; break;
    
        default: trigger_error( 'HOSTNAME is set to an unknown value', E_USER_ERROR );
      }    
    
      return $isdev;
    }
    
    0 讨论(0)
  • 2020-12-08 15:39

    I usually just do something like this:

    if ($_SERVER['HTTP_HOST'] == 'localhost') // or any other host
    {
         // development
    }
    
    else
    {
         // production
    }
    
    0 讨论(0)
提交回复
热议问题