開啟 CodeIgniter Session 自動加載後出現報錯:「In order to use the Session class you are required to set an encryption key」。這是因為 Session 類依賴加密功能,必須配置 encryption_key。
CI Session 類在初始化時檢查加密密鑰:
// system/libraries/Session.php
public function __construct() {
if (empty($this->encryption_key)) {
show_error('In order to use the Session class you are required to set an encryption key in your config file.');
}
// ...
}
application/config/config.php
/* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | If you use the Encryption class or the Session class you | MUST set an encryption key. See the user guide for info. */ $config['encryption_key'] = ''; // 默認空值導致報錯
// 方法一:手動設置(生產環境建議)
$config['encryption_key'] = 'X7k9mP2qR5vW8zA1bC3dE6fG9hJ2kL5';
// 方法二:動態生成(僅開發環境)
$config['encryption_key'] = bin2hex(random_bytes(16));
// 方法三:從環境變量讀取(最佳實踐)
$config['encryption_key'] = getenv('CI_ENCRYPTION_KEY') ?: 'fallback_key_for_dev_only';
# Linux/Mac php -r "echo bin2hex(random_bytes(32)) . PHP_EOL;" # Windows PowerShell php -r "echo bin2hex(random_bytes(32)) . PHP_EOL;"
// application/config/config.php
switch (ENVIRONMENT) {
case 'development':
$config['encryption_key'] = 'dev_key_only_for_local_testing_123456789012';
break;
case 'testing':
$config['encryption_key'] = getenv('CI_TEST_ENCRYPTION_KEY');
break;
case 'production':
$config['encryption_key'] = getenv('CI_PROD_ENCRYPTION_KEY');
break;
}
// 確保生產環境有值
if (ENVIRONMENT === 'production' && empty($config['encryption_key'])) {
die('FATAL: Production encryption key not set!');
}
| 誤區 | 正確做法 |
|---|---|
| 使用簡單字符串如 "secret" | 至少 32 字符高熵隨機字符串 |
| 密鑰硬編碼在代碼中 | 使用環境變量或配置文件(.gitignore) |
| 多項目共用同一密鑰 | 每個項目獨立密鑰 |
| 以為只有加密類需要 | Session、Cookie 加密、CSRF 都需要 |
# 重新訪問頁面或運行測試 php index.php test session_check # 無報錯即成功
更多 CI 配置技巧:《CodeIgniter最佳實踐指南》、《PHP安全配置手冊》