Search code examples
javascriptphphttpcorssame-origin-policy

Determine the current environment and requesting origin - need to define variable


I have almost all of my code complete except for one last variable, $currentEnv = '???' . How do I detect the current environment with this syntax??

/**
     * CORS Implementation to support AJAX requests from mobile site
     * @see http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
     */
    // Define allowed origins per environment
    $allowedOrigins = array(
        'prod' = array(
            'http://m.site.com'
          , 'https://m.site.com'
        )
      , 'staging' = array(
            'http://stg-m.site.com'
          , 'https://stg-m.site.com'
        )
      , 'qa' = array(
            'http://qa-m.site.com'
          , 'https://qa-m.site.com'
        )
    );

    // Determine the current environment and requesting origin
    $httpOrigin = $_SERVER['HTTP_ORIGIN'];
    $currentEnv = "prod"; **// Something that determines the environment...**

    // Allow only if all points match
    if ( isset($allowedOrigins[$currentEnv])
      && in_array($httpOrigin, $allowedOrigins[$currentEnv])
    ){
      header("Access-Control-Allow-Origin: $httpOrigin");
      header("Access-Control-Allow-Methods: POST, GET");
    }

Solution

  • I can't believe I didn't think of this before... SOLUTION:

    /**
    * CORS Implementation to support AJAX requests from mobile site
    * @see http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
    */
    // Define allowed origins per environment
    $allowedOrigins = array(
        'prod' = array(
            'http://m.site.com'
          , 'https://m.site.com'
        )
      , 'staging' = array(
            'http://stg-m.site.com'
          , 'https://stg-m.stie.com'
        )
      , 'qa' = array(
            'http://qa-m.site.com'
          , 'https://qa-m.site.com'
        )
    );
    
    // Determine the current environment and reqesting origin
    switch( $_SERVER['SERVER_NAME'] )
    {
      case 'site.com': // fall-thru
      case 'www.site.com':
        $currentEnv = 'prod';
        break;
      case 'stg.site.com':
        $currentEnv = 'staging';
        break;
      case 'qa.site.com':
        $currentEnv = 'qa';
        break;
      default:
        $currentEnv = 'unknown';
    }
    $httpOrigin = $_SERVER['HTTP_ORIGIN'];
    
    // Allow only if all points match
    if ( isset($allowedOrigins[$currentEnv])
      && in_array($httpOrigin, $allowedOrigins[$currentEnv])
    ){
      header("Access-Control-Allow-Origin: $httpOrigin");
      header("Access-Control-Allow-Methods: POST, GET");
    }
    

    SOLVED!