Javascript 确定当前环境和请求来源-需要定义变量
除了最后一个变量$currentEnv='???'之外,我几乎完成了所有代码。如何使用此语法检测当前环境Javascript 确定当前环境和请求来源-需要定义变量,javascript,php,http,cors,same-origin-policy,Javascript,Php,Http,Cors,Same Origin Policy,除了最后一个变量$currentEnv='???'之外,我几乎完成了所有代码。如何使用此语法检测当前环境 /** * CORS Implementation to support AJAX requests from mobile site * @see http://en.wikipedia.org/wiki/Cross-origin_resource_sharing */ // Define allowed origins per environment
/**
* 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");
}
我不敢相信我以前没有想到这个。。。解决方案:
/**
* 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");
}
解决了 总的来说,应该有更好的方法来做到这一点,但问题是:
$httpOrigin = $_SERVER['HTTP_ORIGIN'];
foreach($allowedOrigins as $env => $url) {
if(in_array($httpOrigin, $url)) {
$currentEnv = $env;
break;
}
}
当前的环境、发展、生产情况如何?谁定义了这个,它应该从哪里来?我正在配置它,这样我只需要在三个代码库中包含一个函数,它将在头中返回原点。我可以简单地将原点定义为“”,但我希望使用一个var来检测环境并根据哪个主机创建它