0.创建users的数据表
CREATE TABLE `users` (
`u_id` int(11) NOT NULL AUTO_INCREMENT,
`u_name` varchar(255) DEFAULT NULL,
`u_email` varchar(255) DEFAULT NULL,
`u_password` varchar(255) DEFAULT NULL,
`u_link` varchar(255) DEFAULT NULL,
`u_date` datetime NOT NULL,
`u_updated` datetime NOT NULL,
PRIMARY KEY (`u_id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
1.新建model,操作数据
app/Models/ModUsers.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class ModUsers extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'u_id';
protected $returnType = 'array';
protected $useTimestamps = true;
protected $allowedFields = ['u_name','u_email','u_password','u_link'];
protected $createdField = 'u_date';
protected $updatedField = 'u_updated';
}
2.修改controller
app/Controllers/User.php
<?php namespace App\Controllers;
use App\Models\ModUsers;
class User extends BaseController{
public function index(){
echo 'I am fine';
}
public function register(){
// echo '注册开始';
helper('form');
return view('signup');
}
public function newuser(){
$myvalues = $this->validate([
'name'=>'required',
'email'=>'required',
'password'=>'required',
]);
if(!$myvalues){//没有通过条件检验
return $this->register();
}else{//通过条件检验后,取值
$myrequest = \Config\Services::request();
$users = new ModUsers();
// echo $myrequest->getVar('name');
// echo $myrequest->getVar('email');
// echo $myrequest->getVar('password');
helper('text');
$data['u_name'] = $myrequest->getVar('name');
$data['u_email'] = $myrequest->getVar('email');
$data['u_password'] = $myrequest->getVar('password');
$data['u_password'] = hash('md5',$data['u_password'] );
$data['u_link'] = random_string('alnum',20);
$myNewuser = $users->insert($data);
if($myNewuser){
echo 'make it to insert';
}else{
echo 'insertion fail';
}
}
}
}
http://localhost/ci4signup/user/register
输入数据,然后查看users,数据插入操作成功。
3. 发邮件测试
PHP的邮件相关的内容与服务器有所联系,比如,SMTP的设置在云平台上和一般服务器上有所差异。鉴于操作上有点麻烦,而且不同的邮件服务器对于权限有不同的规定,PHP的邮件功能要么是测试用,要么是内部用,对外开放用的其实不多。比如,gmail的有需要对账号的安全等级进行设置,有个“Less secure app access”需要激活。这里就略过一些内容。
app/Config/emial.php,等
public $protocol = 'smtp';
/**
* SMTP Server Address
*
* @var string
*/
public $SMTPHost = 'smtp.gmail.com';
/**
* SMTP Username
*
* @var string
*/
public $SMTPUser = '我的gmail邮箱';
public $SMTPPass = '我的gmail邮箱密码';
这一块,我测试过,可以发到我的126邮箱里。
app/controllers/user.php
<?php namespace App\Controllers;
use App\Models\ModUsers;
class User extends BaseController{
public function index(){
echo 'I am fine';
}
public function register(){
// echo '注册开始';
helper('form');
return view('signup');
}
public function newuser(){
$myvalues = $this->validate([
'name'=>'required',
'email'=>'required',
'password'=>'required',
]);
if(!$myvalues){//没有通过条件检验
return $this->register();
}else{//通过条件检验后,取值
$myrequest = \Config\Services::request();
$users = new ModUsers();
// echo $myrequest->getVar('name');
// echo $myrequest->getVar('email');
// echo $myrequest->getVar('password');
helper('text');
$data['u_name'] = $myrequest->getVar('name');
$data['u_email'] = $myrequest->getVar('email');
$data['u_password'] = $myrequest->getVar('password');
$data['u_password'] = hash('md5',$data['u_password'] );
$data['u_link'] = random_string('alnum',20);
$myNewuser = $users->insert($data);
if($myNewuser){
echo 'make it to insert';
}else{
echo 'insertion fail';
}
$email = \Config\Services::email();
$email->setFrom('我的gmail邮箱','Activate the account');
$email->setTo($data['u_email']);
$email->setSubject('Activiate your account');
$email->setMessage($message);
if($email->send())
{
echo 'Email sent successfully';
}else{
echo 'Fail to send email '.$email->printDebugger(['headers']);
}
}
}
}
测试结果如下
4.进一步,随机生成注册链接
常见的注册过程中,服务器往往会发一封带有链接的地址到用户提供邮箱里,这里就生成一个随机地址,插入到邮件里,进行演示。
先添加一列,用来标注是否允许发送邮件。
ALTER TABLE `users` ADD `u_status` INT(5) NOT NULL DEFAULT '0' AFTER `u_updated`;
app/Controllers/User.php
<?php namespace App\Controllers;
use App\Models\ModUsers;
class User extends BaseController{
public function index(){
echo 'I am fine';
}
public function register(){
// echo '注册开始';
helper('form');
return view('signup');
}
public function newuser(){
$myvalues = $this->validate([
'name'=>'required',
'email'=>'required',
'password'=>'required',
]);
if(!$myvalues){//没有通过条件检验
return $this->register();
}else{//通过条件检验后,取值
$myrequest = \Config\Services::request();
$users = new ModUsers();
// echo $myrequest->getVar('name');
// echo $myrequest->getVar('email');
// echo $myrequest->getVar('password');
helper('text');
$data['u_name'] = $myrequest->getVar('name');
$data['u_email'] = $myrequest->getVar('email');
$data['u_password'] = $myrequest->getVar('password');
$data['u_password'] = hash('md5',$data['u_password'] );
$data['u_link'] = random_string('alnum',20);
$myNewuser = $users->insert($data);
if($myNewuser){
echo 'make it to insert';
}else{
echo 'insertion fail';
}
//这里就看得出u_link是个随机生成的链接。更好的实现是通过session来保存一下,并且在一定时间后自动销毁。
$message = 'Please activate the account'.anchor('user/activate/'.$data['u_link'],'Activate account here','');
$email = \Config\Services::email();
$email->setFrom('xx@xx.com','Activate the account');
$email->setTo($data['u_email']);
$email->setSubject('Activiate your account');
$email->setMessage($message);
if($email->send())
{
echo 'Sent successfully';
}else{
$email->printDebugger(['headers']);
}
}
}
public function activate($linkhere){
$user = new ModUsers();
$checklink = $user->where('u_link', $linkhere)->findAll();
if(count($checklink) > 0){
$data['u_status'] = 1;
$activateUser = $user->update($checklink[0]['u_id'],$data);
if($activateUser){
echo 'ok';
}
else{
echo 'failed';
}
}else{
echo 'expired';
}
}
}
注意:这里的代码仅仅做说明,我在操作过程中,126邮箱收到了内容是:
Please activate the accountActivate
account here
能看得出该链接不是个有效的www链接,复制粘贴到浏览器中,回车,会调用activate($linkhere)方法,该方法为了修改是否已经激活该链接,结果如下:
然后再看看数据库,会发现最后的一条数据u_status是1,成功。
5.再次扩展,杜绝重复注册
这里,以用户名为依据,杜绝重复的用户名注册。
<?php namespace App\Controllers;
use App\Models\ModUsers;
class User extends BaseController{
public function index(){
echo 'I am fine';
}
public function register(){
// echo '注册开始';
helper('form');
return view('signup');
}
public function newuser(){
$myvalues = $this->validate([
'name'=>'required',
'email'=>'required',
'password'=>'required',
]);
if(!$myvalues){//没有通过条件检验
return $this->register();
}else{//通过条件检验后,取值
$myrequest = \Config\Services::request();
$users = new ModUsers();
// echo $myrequest->getVar('name');
// echo $myrequest->getVar('email');
// echo $myrequest->getVar('password');
helper('text');
$data['u_name'] = $myrequest->getVar('name');
$data['u_email'] = $myrequest->getVar('email');
$data['u_password'] = $myrequest->getVar('password');
$data['u_password'] = hash('md5',$data['u_password'] );
$data['u_link'] = random_string('alnum',20);
//这里就看得出u_link是个随机生成的链接。更好的实现是通过session来保存一下,并且在一定时间后自动销毁。
$message = 'Please activate the account'.anchor('user/activate/'.$data['u_link'],'Activate account here','');
$checkUserExists = $users->where('u_email',$data['u_email'])->findAll();
if(count($checkUserExists) > 0){
echo 'The email exists';
}else{
$myNewuser = $users->insert($data);
if($myNewuser){
echo 'make it to insert';
$email = \Config\Services::email();
$email->setFrom('guoxingyao@gmail.com','Activate the account');
$email->setTo($data['u_email']);
$email->setSubject('Activiate your account');
$email->setMessage($message);
if($email->send())
{
echo 'Email sent successfully';
}else{
echo 'Fail to send email '.$email->printDebugger(['headers']);
}
}else{
echo 'insertion fail';
}
}
}
}
public function activate($linkhere){
$user = new ModUsers();
$checklink = $user->where('u_link', $linkhere)->findAll();
if(count($checklink) > 0){
$data['u_status'] = 1;
$activateUser = $user->update($checklink[0]['u_id'],$data);
if($activateUser){
echo 'ok';
}
else{
echo 'failed';
}
}else{
echo 'expired';
}
}
}
6.用session传递数据
session是CI框架常见的一个功能,在传递数据时至关重要。
$session = \Config\Services::session();是基础语法。
app/controllers/user.php
<?php namespace App\Controllers;
use App\Models\ModUsers;
class User extends BaseController{
public function index(){
echo 'I am fine';
}
public function register(){
// echo '注册开始';
helper('form');
$session = \Config\Services::session();
$data['message']=$session->getFlashdata('message');
return view('signup',$data);
}
public function newuser(){
$myvalues = $this->validate([
'name'=>'required',
'email'=>'required',
'password'=>'required',
]);
if(!$myvalues){//没有通过条件检验
return $this->register();
}else{//通过条件检验后,取值
$myrequest = \Config\Services::request();
$session = \Config\Services::session();
$users = new ModUsers();
// echo $myrequest->getVar('name');
// echo $myrequest->getVar('email');
// echo $myrequest->getVar('password');
helper('text');
$data['u_name'] = $myrequest->getVar('name');
$data['u_email'] = $myrequest->getVar('email');
$data['u_password'] = $myrequest->getVar('password');
$data['u_password'] = hash('md5',$data['u_password'] );
$data['u_link'] = random_string('alnum',20);
//这里就看得出u_link是个随机生成的链接。更好的实现是通过session来保存一下,并且在一定时间后自动销毁。
$message = 'Please activate the account'.anchor('user/activate/'.$data['u_link'],'Activate account here','');
$checkUserExists = $users->where('u_email',$data['u_email'])->findAll();
if(count($checkUserExists) > 0){
$session->setFlashdata('message','The email is already used');
return redirect()->to(site_url('user/newuser'));
// echo 'The email exists';
}else{
$myNewuser = $users->insert($data);
if($myNewuser){
echo 'make it to insert';
$email = \Config\Services::email();
$email->setFrom('guoxingyao@gmail.com','Activate the account');
$email->setTo($data['u_email']);
$email->setSubject('Activiate your account');
$email->setMessage($message);
if($email->send())
{
echo 'Email sent successfully';
}else{
$session->setFlashdata('message','The email sending fails');
return redirect()->to(site_url('user/newuser'));
}
}else{
$session->setFlashdata('message','The insertion fails');
return redirect()->to(site_url('user/newuser'));
}
}
}
}
public function activate($linkhere){
$user = new ModUsers();
$checklink = $user->where('u_link', $linkhere)->findAll();
if(count($checklink) > 0){
$data['u_status'] = 1;
$activateUser = $user->update($checklink[0]['u_id'],$data);
if($activateUser){
echo 'ok';
}
else{
echo 'failed';
}
}else{
echo 'expired';
}
}
}
http://localhost/ci4signup/user/newuser测试一下,输入一个已经存在的用户名,然后返回错误,然后再刷新一下,该错误消失。
这部分主要讲解的是利用sessoin的fladhdata进行一次错误的提示。
7.完成登陆功能
app/Views/signin.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register a New User</title>
</head>
<body>
<?php
if(isset($message) && !empty($message)){
echo '<div>'.$message.'</div>';
}
echo \Config\Services::validation()->listErrors();
echo form_open('user/checkuser');
echo 'Enter your password ', form_input('password','',''), '<br>';
echo 'Enter your email ', form_input('email','',''), '<br>';
echo form_submit('','Login');
echo form_close();
?>
</body>
</html>
app/controllers/user.php
<?php namespace App\Controllers;
use App\Models\ModUsers;
class User extends BaseController{
public function index(){
echo 'I am fine';
}
public function register(){
// echo '注册开始';
helper('form');
$session = \Config\Services::session();
$data['message']=$session->getFlashdata('message');
return view('signup',$data);
}
public function newuser(){
$myvalues = $this->validate([
'name'=>'required',
'email'=>'required',
'password'=>'required',
]);
if(!$myvalues){//没有通过条件检验
return $this->register();
}else{//通过条件检验后,取值
$myrequest = \Config\Services::request();
$session = \Config\Services::session();
$users = new ModUsers();
// echo $myrequest->getVar('name');
// echo $myrequest->getVar('email');
// echo $myrequest->getVar('password');
helper('text');
$data['u_name'] = $myrequest->getVar('name');
$data['u_email'] = $myrequest->getVar('email');
$data['u_password'] = $myrequest->getVar('password');
$data['u_password'] = hash('md5',$data['u_password'] );
$data['u_link'] = random_string('alnum',20);
//这里就看得出u_link是个随机生成的链接。更好的实现是通过session来保存一下,并且在一定时间后自动销毁。
$message = 'Please activate the account'.anchor('user/activate/'.$data['u_link'],'Activate account here','');
$checkUserExists = $users->where('u_email',$data['u_email'])->findAll();
if(count($checkUserExists) > 0){
$session->setFlashdata('message','The email is already used');
return redirect()->to(site_url('user/newuser'));
// echo 'The email exists';
}else{
$myNewuser = $users->insert($data);
if($myNewuser){
echo 'make it to insert';
$email = \Config\Services::email();
$email->setFrom('guoxingyao@gmail.com','Activate the account');
$email->setTo($data['u_email']);
$email->setSubject('Activiate your account');
$email->setMessage($message);
if($email->send())
{
echo 'Email sent successfully';
}else{
$session->setFlashdata('message','The email sending fails');
return redirect()->to(site_url('user/newuser'));
}
}else{
$session->setFlashdata('message','The insertion fails');
return redirect()->to(site_url('user/newuser'));
}
}
}
}
public function activate($linkhere){
$user = new ModUsers();
$checklink = $user->where('u_link', $linkhere)->findAll();
if(count($checklink) > 0){
$data['u_status'] = 1;
$activateUser = $user->update($checklink[0]['u_id'],$data);
if($activateUser){
echo 'ok';
}
else{
echo 'failed';
}
}else{
echo 'expired';
}
}
public function signin(){
$session = \Config\Services::session();
$data['message']=$session->getFlashdata('message');
helper('form');
return view('signin',$data);
}
public function checkuser(){
$myrequest = \Config\Services::request();
$session = \Config\Services::session();
$myvalues = $this->validate([
'email'=>'required',
'password'=>'required',
]);
if(!$myvalues){//没有通过条件检验
return $this->signin();
}else{
$users = new ModUsers();
helper('text');
$data['u_email'] = $myrequest->getVar('email');
$data['u_password'] = $myrequest->getVar('password');
$data['u_link'] = random_string('alnum',20);
$allUsers = $users->where('u_email',$data['u_email'])->findAll();
if(count($allUsers) > 0){
if($data['u_password'] == $allUsers[0]['u_password']){
echo 'login invalid';
}else{
echo 'login valid';
}
}else{
}
}
}
}
至此,一个注册登录的小例子完工。后续可能的改进包括引入css美化,js,以及代码的修改。以及登出功能:
$session->destroy();
return redirect()->to('user/signin');
齐活。