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.
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