如何在 CodeIgniter 中正确将 OTP 插入数据库

7次阅读

如何在 CodeIgniter 中正确将 OTP 插入数据库

本文解决 codeigniter 项目中用户注册时 otp 生成成功但未写入数据库的问题,核心原因是模型调用参数错误——向 insert() 方法传递了三个参数,而实际只接收两个,导致 otp 字段被忽略。

在您提供的控制器代码中,关键问题出现在这一行:

$data = $this->user_model->insert('cred', ['email' => $to], ['otp' => ($newotp)]);

该调用试图传入 三个参数:表名 ‘cred‘、第一个数据数组 [’email’ => $to]、第二个数据数组 [‘otp’ => $newotp]。然而,您的模型方法定义为:

public function insert($table, $data = array())

它仅接受 两个参数:$table 和 $data。因此,第三个参数 [‘otp’ => …] 被完全忽略,最终只有 email 被插入,OTP 丢失。

✅ 正确做法是:将所有字段合并为一个关联数组,一次性传入:

$data = $this->user_model->insert('cred', [     'email' => $to,     'otp'   => $newotp ]);

同时,建议优化模型中的 insert() 方法,使其更健壮、可复用,并明确返回布尔值或插入 ID:

// user_model.php public function insert($table, $data = []) {     if (empty($data) || !is_array($data)) {         return FALSE;     }      $this->db->insert($table, $data);      if ($this->db->affected_rows() === 1) {         return $this->db->insert_id(); // 返回新记录 ID(可选)     }      return FALSE; }

⚠️ 其他重要注意事项:

  • 安全性提醒:当前逻辑将 OTP 直接作为“密码”明文发送至邮箱,存在严重安全隐患。生产环境应:
    • 使用哈希(如 password_hash($newotp, PASSword_DEFAULT))存储 OTP;
    • 设置 OTP 有效期(如 5 分钟),并添加 expires_at 时间戳字段;
    • 验证时比对哈希值 + 检查时效性,而非明文匹配。
  • OTP 生成增强:当前使用 rand() 生成 8 位纯数字 OTP,建议改用密码学安全函数(CodeIgniter 3.1.11+ 支持 random_string(‘nozero’, 6)),或升级至 CI4 使用 random_bytes()。
  • 邮件发送健壮性:$this->Others->send_email() 返回值未校验。应在发送失败时记录日志或提示用户重试,避免 OTP 已生成却未送达。

? 小结:修复的核心是统一数据结构、严格匹配方法签名;长远来看,需补充时效控制、加密存储与错误处理,才能构建安全可靠的 OTP 认证流程。

text=ZqhQzanResources