🔥

CodeIgniter4 .env ファイルを使った encrypt 設定でハマった

2022/08/31に公開
2

動作確認

  • CodeIgniter 4.2.5

Database.php で設定する場合

CodeIgniter3 の時のように Database.php で設定する例

app/Config/Database.php
public $default = [
    // ...
    'encrypt' => [
        'ssl_ca' => 'hoge/fuga/piyo.pem',
	'ssl_verify' => false,
    ],
    // ...
];

.env で設定する場合

今回ハマったパターン

.env
database.default.encrypt.ssl_ca = hoge/fuga/piyo.pem
database.default.encrypt.ssl_verify = false
app/Config/Database.php
public $default = [
    // ...
    'encrypt' => false,
    // ...
];

エラー内容

CodeIgniter\Database\Exceptions\DatabaseException #8
Unable to connect to the database.
Main connection [MySQLi]: Connections using insecure transport are prohibited while --require_secure_transport=ON.

以下のように encrypt のプロパティを .env で設定したいキーを持つ連想配列にすることで解決

app/Config/Database.php
public $default = [
    // ...
    'encrypt' => [
        'ssl_ca' => '',
	'ssl_verify' => '',
    ],
    // ...
];

データベースの設定を確認

$db_config = new \Config\Database();
dd($db_config);
// encrypt => array (2)
//     ssl_ca => string (18) "hoge/fuga/piyo.pem"
//     ssl_verify => boolean false

参考

https://codeigniter4.github.io/CodeIgniter4/general/configuration.html#environment-variables-as-replacements-for-data

It is very important to always remember that environment variables contained in your .env are only replacements for existing data. This means that you cannot expect to fill your .env with all the replacements for your configurations but have nothing to receive these replacements in the related configuration file(s).

The .env only serves to fill or replace the values in your configuration files. That said, your configuration files should have a container or receiving property for those. Adding so many variables in your .env with nothing to contain them in the receiving end is useless.

Simply put, you cannot just put app.myNewConfig = foo in your .env and expect your Config\App to magically have that property and value at run time.

Discussion

kenjiskenjis

これ、

'encrypt' => [],

で動作しますか?

naentenaente
app/Config/Database.php
public $default = [
    // ...
    'encrypt' => [],
    // ...
];

の場合

$db_config = new \Config\Database();
dd($db_config);
// encrypt => array (0)

となり、正しく設定できていませんでしたので
記事を修正しました。

ご指摘いただきありがとうございました。