下面是一个使用CodeIgniter框架实现登录、注册和验证电子邮件(使用Gmail)的示例代码:
- 在CodeIgniter框架中创建一个新的控制器(例如,AuthController.php),并添加以下代码:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class AuthController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('email');
$this->load->model('AuthModel'); // 替换为你的用户认证模型
}
public function register()
{
// 获取注册表单数据
$name = $this->input->post('name');
$email = $this->input->post('email');
$password = $this->input->post('password');
// 创建一个随机的验证令牌
$token = md5(uniqid());
// 将用户数据插入数据库
$user_id = $this->AuthModel->register($name, $email, $password, $token);
// 发送验证邮件
$this->email->from('your-email@gmail.com', 'Your Name');
$this->email->to($email);
$this->email->subject('Account Activation');
$this->email->message('Click on the link to activate your account: ' . base_url('auth/activate/' . $token));
$this->email->send();
// 显示注册成功消息
echo 'Registration successful. Please check your email to activate your account.';
}
public function activate($token)
{
// 根据验证令牌激活用户账户
$user_id = $this->AuthModel->activate($token);
if ($user_id) {
// 显示账户激活成功消息
echo 'Account activated successfully.';
} else {
// 显示账户激活失败消息
echo 'Invalid activation token.';
}
}
public function login()
{
// 获取登录表单数据
$email = $this->input->post('email');
$password = $this->input->post('password');
// 验证用户登录
$user = $this->AuthModel->login($email, $password);
if ($user) {
// 登录成功,将用户数据存储在session中
$this->session->set_userdata('user', $user);
// 重定向到用户的个人资料页面
redirect('profile');
} else {
// 登录失败,显示错误消息
echo 'Invalid email or password.';
}
}
public function logout()
{
// 从session中删除用户数据
$this->session->unset_userdata('user');
// 重定向到登录页面
redirect('login');
}
}
- 在CodeIgniter框架中创建一个新的模型(例如,AuthModel.php),并添加以下代码:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class AuthModel extends CI_Model {
public function register($name, $email, $password, $token)
{
// 将用户数据插入数据库
// 在此处执行插入数据库的操作,例如使用CodeIgniter的Active Record类或手动编写SQL查询
// 返回插入的用户ID
return $user_id;
}
public function activate($token)
{
// 根据验证令牌激活用户账户
// 在此处执行更新数据库的操作,将用户的激活状态设置为已激活,例如使用CodeIgniter的Active Record类或手动编写SQL查询
if ($activation_successful) {
// 返回用户ID
return $user_id;
} else {
// 返回false表示激活失败
return false;
}
}
public function login($email, $password)
{
// 根据email和password验证用户登录
// 在此处执行查询数据库的操作,例如使用CodeIgniter的Active Record类或手动编写SQL查询
if ($login_successful) {
// 返回用户数据
return $user;
} else {
// 返回false表示登录失败
return false;
}
}
}
请注意,示例代码中使用