douzhe3516 2018-06-12 04:53
浏览 394
已采纳

在Yii2中使用$ _SERVER ['SERVER_NAME']检测环境是否正确

if ($_SERVER['SERVER_NAME'] == 'localhost' || $_SERVER['SERVER_NAME'] == '127.0.0.1') 
{
    defined('YII_DEBUG') or define('YII_DEBUG', true);
    defined('YII_ENV') or define('YII_ENV', 'dev');
}

require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
require __DIR__ . '/../config/bootstrap.php';

if(YII_ENV == 'prod')
{
    $config = yii\helpers\ArrayHelper::merge(
        require __DIR__ . '/../../common/config/main.php',
        require __DIR__ . '/../config/main.php'
    );
}
else
{
    $config = yii\helpers\ArrayHelper::merge(
       require __DIR__ . '/../../common/config/main.php',
       require __DIR__ . '/../../common/config/main-local.php',
       require __DIR__ . '/../config/main.php',
       require __DIR__ . '/../config/main-local.php'
   );
}

I am trying to use multiple environments but don't what to change all the time in files so I use if condition in my index.php file and its working but I don't know it is the right way or not.

  • 写回答

1条回答 默认 最新

  • doucanrui1735 2018-06-12 07:39
    关注

    No, it is not. And this is a potential security issue - $_SERVER['SERVER_NAME'] can be spoofed, so someone may access your remote production server using localhost as a host name. If you're not validating host name at webserver level, then he will see your website in debug mode. From $_SERVER['SERVER_NAME'] docs:

    Note: Under Apache 2, you must set UseCanonicalName = On and ServerName. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts.


    You should probably keep environment-specific settings/constants in separate file outside of version control. For example in config/environment-local.php. And setup it manually on every instance. You may also use Composer hooks to copy default content of this file - I implemented something like that in my template. Then require this file on the top of your index.php file instead of your condition:

    require __DIR__ . '/../config/environmen-local.php';
    
    require __DIR__ . '/../../vendor/autoload.php';
    require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
    require __DIR__ . '/../../common/config/bootstrap.php';
    require __DIR__ . '/../config/bootstrap.php';
    
    // rest of bootstrap
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器