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

在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 请问各位,如何在Jetson nano主控板的Ubuntu系统中安装PyQt5
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位
  • ¥15 为何重叠加权后love图的SMD与svyCreateTableOne函数绘制基线表的不一致
  • ¥150 求 《小魔指》街机游戏机整合模拟软件