Codeigniter 3.x使用表单验证登录-锅炉板 [英] Codeigniter 3.x Login with Form Validation -Boiler plate

查看:84
本文介绍了Codeigniter 3.x使用表单验证登录-锅炉板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我一直在阅读来自不同新手的几个有关Codeigniter中的登录和验证的问题,其中一些问题混合了JavaScript和J查询. Codeigniter本身提供了可靠的表单验证以及自定义错误设置支持.我已决定与您分享我创建的登录样板中启动Codeigniter的最简单方法,并与您分享.它有

I have been reading couple of questions here from different newbies about Login and validation in codeigniter, some have mixed JavaScript and J-query. Codeigniter itself provide a robust form validation along with custom error setting support. I have decided to share with you the easiest way to kickstart in codeigniter with login boilerplate which I have created and I am sharing it with you. It has

控制器 登录

型号:Login_model

Model: Login_model

浏览次数:登录并成功

基本配置

推荐答案

步骤1

官方网站

第2步

在本地主机根目录中的文件夹中解压缩. (xampp中的htdocs和wamp中的www)

Extract in a folder in your localhost root. (htdocs in xampp and www in wamp)

步骤3.配置

打开您已在其中提取了codeigniter的文件夹 应用程序->配置-> autoload.php.转到第55行并自动加载这两个库

Open the folder you have extracted the codeigniter in go to application->config->autoload.php. Go to line 55 and autoload these two libraries

$autoload['libraries'] = array('database', 'session');

转到第67行并加载两个助手

Go to line 67 and load two helpers

$autoload['helper'] = array('url', 'file');

保存文件,然后转到应用程序-> config-> config.php

Save the file and now go the application->config->config.php

将第19行的基本URL设置为

Set Base URL on line 19 as

$config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/folder_name/';

在第31行,从值中删除index.php并将其更​​改为

On line 31 remove the index.php from value and change it to

$config['index_page'] = '';

第49行,将uri_protocol从AUTO设置为REQUEST_URI

on line 49 set uri_protocol from AUTO to REQUEST_URI

$config['uri_protocol'] = 'REQUEST_URI';

第229行设置一个加密密钥

on line 229 set an encryption key

$config['encryption_key'] = '!@#$%^&*()ASDFGHJKL:ZXCVBNM<>QWERTYUIOP';
// I recommend you create a hash and place it here

保存文件

第4步.htaccess

在codeigniter安装文件夹的根目录中,创建一个.htaccess文件,然后在其中写入以下内容并保存

On the root of codeigniter installation folder create an .htaccess file write following in it and save

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

步骤5.创建数据库

打开您的phpmyadmin或mysql终端创建一个数据库,在其中创建一个表用户,您可以使用以下查询

Open your phpmyadmin or mysql terminal create a database , create a table users in it , you can use following query

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `status` enum('pending','approved') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

步骤-6.将数据库连接到Codeigniter

转到application-> config-> database.php.假设它是全新安装,则您尚未创建任何环境.转到第52行,将四行更改为

Go to application->config->database.php. Assuming its a fresh install and you haven't created any environments. Go to line 52 and change the four lines to

$db['default']['username'] = 'username'; // will be root if you have xampp
$db['default']['password'] = 'password'; // will be empty if you haven't set
$db['default']['database'] = 'your_database_name';
$db['default']['dbdriver'] = 'mysqli'; // changed from mysql to mysqli

步骤7.视图

源代码

步骤8.控制器

class Login extends CI_Controller {
function __construct()
{
    parent::__construct();
    $this->load->model('Login_model');
    $this->load->library('form_validation');
}

public function index()
{
    if($this->isLoggedin()){ redirect(base_url().'login/dashboard');}
    $data['title']='Login Boiler Plate';
    if($_POST)
    {
        $config=array(
            array(
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'password',
                'label' => 'Password',
                'rules' => 'trim|required'
            )
        );
        $this->form_validation->set_rules($config);
        if ($this->form_validation->run() == false) {
            // if validation has errors, save those errors in variable and send it to view
            $data['errors'] = validation_errors();
            $this->load->view('login',$data);
        } else {
            // if validation passes, check for user credentials from database
            $user = $this->Login_model->checkUser($_POST);
            if ($user) {
            // if an record of user is returned from model, save it in session and send user to dashboard
                $this->session->set_userdata($user);
                redirect(base_url() . 'Login/dashboard');
            } else {
            // if nothing returns from model , show an error
                $data['errors'] = 'Sorry! The credentials you have provided are not correct';
                $this->load->view('login',$data);
            }
        }

    }
    else
    {
        $this->load->view('login',$data);
    }

}
public function change_password()
{
    if($this->isLoggedin()){
        $data['title']='Change Password';
        if($_POST)
        {
            $config=array(
                array(
                    'field' => 'old_password',
                    'label' => 'Old Password',
                    'rules' => 'trim|required|callback_checkPassword'
                ),
                array(
                    'field' => 'password',
                    'label' => 'Password',
                    'rules' => 'trim|required'
                ),
                array(
                    'field' => 'conf_password',
                    'label' => 'Confirm Password',
                    'rules' => 'trim|required|matches[password]'
                )
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == false)
            {
                // if validation has errors, save those errors in variable and send it to view
                $data['errors'] = validation_errors();
                $this->load->view('change_password',$data);
            }
            else
            {
                // if validation passes, check for user credentials from database
                $this->Login_model->updatePassword($_POST['password'],$this->session->userdata['id']);
                $this->session->set_flashdata('log_success','Congratulations! Password Changed');
                redirect(base_url() . 'Login/dashboard');
            }

        }
        else
        {
            $this->load->view('change_password',$data);
        }
    }
    else
    {
        redirect(base_url().'Login');
    }

}

public function dashboard()
{
    if($this->isLoggedin())
    {
        $data['title']='Welcome! You are logged in';
        $this->load->view('success',$data);
    }
    else
    {
        redirect(base_url().'Login');
    }
}

public function logout()
{
    $this->session->sess_destroy();
    redirect(base_url().'Login');
}

public function isLoggedin()
{
    if(!empty($this->session->userdata['id']))
    {
        return true;
    }
    else
    {
        return false;
    }
}

}

步骤8.模型

class Login_model extends CI_Model{
function __construct(){
    parent::__construct();
}

public function checkUser($data)
{
    $st=$this->db->SELECT('*')->from('users')
                    ->WHERE('username',$data['username'])
                    ->WHERE('password',sha1(md5($data['password'])))
                    ->get()->result_array();
    if(count($st)>0)
    {
        return $st[0];
    }
    else
    {
        return false;
    }
}
public function checkPassword($str)
{
    $st=$this->db->SELECT('*')->from('users')
        ->WHERE('id',$this->session->userdata['id'])
        ->WHERE('password',sha1(md5($str)))
        ->get()->result_array();
    if(count($st)>0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

public function updatePassword($password,$id)
{
    $pass=array(
        'password' => sha1(md5($password))
    );
    $this->db->WHERE('id',$id)->update('users',$pass);
}
}

步骤9.测试

在Phpmyadmin中打开数据库,并使用以下查询将示例数据插入表中

Open Database in Phpmyadmin and insert sample data in to your table using following query

INSERT INTO `users` (`id`, `username`, `password`, `fullname`, `status`) 
VALUES
(1, 'john', '56f5950b728849d0b97c1bccf1691c090ab6734c', 'John Vick', 
'approved');

测试1 空提交

它将产生错误,我们将其存储在Controller中的错误索引中,并将其传递给视图,并在该值存在的情况下在视图中显示.

It will produce the error, which we are storing in an errors index in Controller, passing it to view and displaying it in the view if the value exists.

测试2.凭证错误

测试3.正确的凭据

用户名:john 密码:约翰

Username: john Password: john



成功查看源代码

警报!

这是初学者的基本代码,还有很多改进空间,例如安全性功能和加密

This is a basic code for kick starters and there is a lot more room for improvements like Security Features and Encryption

完整的源代码

您可以从 Boiler-Plates上的Git下载完整的源代码. -Codeigniter-3.x登录

这篇关于Codeigniter 3.x使用表单验证登录-锅炉板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆