Codeigniter 4基础教程(11)-- 注册登陆案例(1)

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');

齐活。

codeigniter 实现登陆 后台auth权限 管理员管理 项目文件请参考 根目录下的CI文件夹 个人娱乐,使用CI框架进行开发一个含有登陆,auth权限验证,后台管理员管理登陆的简单项目 1:数据库结构如下(使用mysql) /* Navicat Premium Data Transfer Source Server : mysql_localhot Source Server Type : MySQL Source Server Version : 50624 Source Host : localhost Source Database : codeigniter Target Server Type : MySQL Target Server Version : 50624 File Encoding : utf-8 Date: 09/28/2015 17:07:46 PM */ SET FOREIGN_KEY_CHECKS = 0; -- Table structure for auth_group DROP TABLE IF EXISTS auth_group; CREATE TABLE auth_group ( id mediumint(8) unsigned NOT NULL AUTO_INCREMENT, title char(100) NOT NULL DEFAULT '', status tinyint(1) NOT NULL DEFAULT '1', rules varchar(256) NOT NULL DEFAULT '', PRIMARY KEY (id) ) ENGINE=MyISAM AUTO_INCREMENT=44 DEFAULT CHARSET=utf8; -- Table structure for auth_group_access DROP TABLE IF EXISTS auth_group_access; CREATE TABLE auth_group_access ( uid mediumint(8) unsigned NOT NULL, group_id mediumint(8) unsigned NOT NULL, UNIQUE KEY uid_group_id (uid,group_id), KEY uid (uid), KEY group_id (group_id) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- Table structure for auth_rule DROP TABLE IF EXISTS auth_rule; CREATE TABLE auth_rule ( id mediumint(8) unsigned NOT NULL AUTO_INCREMENT, name char(80) NOT NULL DEFAULT '', title varchar(255) NOT NULL DEFAULT '', type tinyint(1) NOT NULL DEFAULT '1', status tinyint(1) NOT NULL DEFAULT '1', condition char(100) NOT NULL DEFAULT '', parent_id mediumint(8) DEFAULT '0', sort mediumint(8) DEFAULT '1', display tinyint(1) NOT NULL DEFAULT '1' COMMENT '1:显示 0:不显示', class varchar(64) DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY name (name) ) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- Table structure for user DROP TABLE IF EXISTS user; CREATE TABLE user ( id int(11) unsigned NOT NULL AUTO_INCREMENT, username varchar(255) NOT NULL, password varchar(64) NOT NULL, email char(100) DEFAULT NULL, mobile char(15) DEFAULT NULL, reg_ip varchar(15) DEFAULT NULL, reg_time int(10) DEFAULT NULL, last_login_time int(10) DEFAULT NULL, last_login_ip varchar(15) DEFAULT NULL, login_count int(11) DEFAULT NULL, update_time int(10) DEFAULT NULL, status enum('1','0') DEFAULT '1' COMMENT '1:激活 0:禁用', del enum('0','1') DEFAULT '0' COMMENT '1:删除', role tinyint(2) DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; SET FOREIGN_KEY_CHECKS = 1; 2:了解该项目主要是如何熟悉一个新框架的工作原理,如果快速开发,怎样搭建一个项目。 1):框架的layout(网上查找,主要有两种方式,比较方便是通过写layout类),如下:admin/libraries/Layout.php 在Controller中定义公共类My_Controller继承CI_Controller,在构造函数中直接加载,如下:admin/controllers/MY_Controller.php 2):在ci如何加载css,js,image等等公共文件,在对应的模块中helper中可以扩展url,我的扩展如下(我是使用bootstrap进行搭建后台):admin/helpers/MY_url_helper.php 3):在layout定义layout视图文件,具体看code 注意:加载url中助手类中自定义方法,需要$this->load->helper('url');例如 3,具体的ci项目是如何进行工作,参考codeigniter手册以及项目代码 4,时间匆忙,也属于学习ci框架阶段,可能有错误或者code有问题的地方,尽请谅解,后面继续完善
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值