github project url:https://github.com/luzhaochun/Codeigniter-login-auth-admin/tree/master/ci(最新)
工作之闲暇时间,研究下codeigniter,加了一个多模块admin后台,做了一个简单的后台
总的感觉的ci框架在快速扩展方面和数据库操作不是很智能,可能需要进一步了解。
简单的进行搭建了一个后台,使用bootstrap css模板,常用的一些的js插件:jquery ui,layer等等
一个简单的后台登陆,管理员操作,auth权限验证(未完成所有,由于逻辑不是很复杂,如有参考者,自行完成),主要熟悉ci工作原理,快速搭建一个网站项目。
1,登陆基本代码:
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Login extends CI_Controller{
var $data = [];
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user');
$this->load->helper('url');
$this->load->helper('cookie');
}
public function index(){
if($this->user->is_logged_in()){
redirect('index');
}
$this->load->view('login');
}
public function checkLogin(){
if($this->user->is_logged_in()){
redirect('index');
}
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run()){
$username = $this->input->post('username');
$password = $this->input->post('password');
if($row = $this->user->get_by_username($username)){
if($this->user->check_password($password,$row['password'])){
$this->user->allow_pass($row);
if(!empty($this->input->post('remember'))){
// $this->input->set_cookie("username",$row['username'],3600*24*7);
// $this->input->set_cookie("password",$row['password'],3600*24*7);
// $this->input->set_cookie("user_id",$row['id'],3600*24*7);
set_cookie("user_id",$this->session->userdata('logged_in'),3600*24*7);
set_cookie("username",$this->session->userdata('user'),3600*24*7);
// set_cookie("password",$row['password'],3600*24*7);
// set_cookie("user_id",$row['id'],3600*24*7);
}
redirect('index');
}else{
$this->data['error'] = 'Invalid username or password';
}
}else{
$this->data['error'] = 'Username not found';
}
}
$this->load->view('login', $this->data);
}
public function logout(){
$this->user->remove_pass();
$this->load->view('login');
}
}
2,登陆设计到user表 所用的model:user.php中部分代码:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class user extends CI_Model{
protected $table = 'user';
protected $max_idle_time = 300; // allowed idle time in secs, 300 secs = 5 minute
public function __construct() {
parent::__construct();
}
function get_by_username($username){
//$this->db->last_query(); get last query way
if(!empty($username)){
$this->db->where('username',$username);
$this->db->or_where('email',$username);
$this->db->or_where('mobile',$username);
$query = $this->db->get($this->table,1);
if($query->num_rows()>0){
return $query->row_array();
}else{
return false;
}
}
return false;
}
function check_password($password,$hash_password){
list($salt,$hash) = explode('.', $hash_password);
$hash2 = $salt .'.'.md5($salt.$password);
return ($hash_password == $hash2);
}
function allow_pass($user_data){
$this->session->set_userdata(array('logged_in' => 'yes', 'user' => $user_data));
}
// Generate hashed password
function hash_password($password) {
$salt = $this->generate_salt();
return $salt . '.' . md5($salt . $password);
}
// create salt for password hashing
private function generate_salt($length = 10) {
$characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$i = 0;
$salt = "";
while ($i < $length) {
$salt .= $characterList{mt_rand(0, (strlen($characterList) - 1))};
$i++;
}
return $salt;
}
function is_logged_in(){
$logged_in = $this->session->userdata('logged_in');
$user = $this->session->userdata('user');
if($logged_in == 'yes'){
$this->allow_pass($user);
return true;
}else{
$this->remove_pass();
return false;
}
}
function remove_pass() {
$this->session->unset_userdata('user');
$this->session->unset_userdata('logged_in','');
}
public function userList(){
$this->db->where('status',1);
$query = $this->db->get($this->table);
return $query->result_array();
}
public function get_admin_info_by_id($id){
$this->db->where('id', $id);
$query = $this->db->get($this->table);
return $query->row_array();
}
}
3,在登陆过程中,我们可能涉及到类库扩展,主要是library和helper,当然有的朋友喜欢自定义logic,extend...个人习惯吧,对于helper,library文件中扩展的类库,尽量与系统类库的对应的文件名一致,就不需要再config中autoload.php再去配置,具体看项目要求吧(对于ci配置文件,自己去研究下,大部分框架大同小异,下面是扩展的url 助手类:MY_url_helper.php(MY__前缀在配置文件中自己修改,
<?php
/**
* CodeIgniter URL Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/helpers/url_helper.html
*/
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
if (!function_exists('base_url')) {
/**
* Base URL
*
* Create a local URL based on your basepath.
* Segments can be passed in as a string or an array, same as site_url
* or a URL to a file can be passed in, e.g. to an image file.
*
* @param string $uri
* @param string $protocol
* @return string
*/
function base_url($uri = '', $protocol = NULL) {
return get_instance()->config->base_url($uri, $protocol);
}
}
if (!function_exists('css_url')) {
function css_url($uri = '') {
$CI = & get_instance();
$css_string = "<link rel='stylesheet' type='text/css' href='" . $CI->config->base_url("/../public/admin/css" . $uri) . "' media='all'>";
return $css_string;
}
}
if (!function_exists('javascript_url')) {
function javascript_url($uri = '') {
$CI = & get_instance();
$javascript_string = "<script type='text/javascript' src='" . base_url("/../public/admin/javascript" . $uri) . "'></script>";
return $javascript_string;
}
}
if (!function_exists('bootstrap_url')) {
function bootstrap_url($uri = '',$type = 'css') {
$CI = & get_instance();
if($type == 'css'){
$return_string = "<link rel='stylesheet' type='text/css' href='" . $CI->config->base_url("/../public/admin/bootstrap" . $uri) . "' media='all'>";
}elseif($type == 'javascript'){
$return_string = "<script type='text/javascript' src='" . base_url("/../public/admin/bootstrap" . $uri) . "'></script>";
}else{
$return_string = "<link rel='stylesheet' type='text/css' href='" . $CI->config->base_url("/../public/admin/bootstrap" . $uri) . "' media='all'>";
}
return $return_string;
}
}
4:对于后台中layout我们如何去实现,这个应该不用解释了,网上应该可以搜出一大堆这方面介绍。
在library中定义Layout.php:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Layout {
public $layout;
function __construct($params = array('main')) {
//本来是想在controller中加载这个类的时候顺便给构造函数传参设置要加载的布局文件,
//结果看文档好像$this -> load -> library('**','**')的第二个参数必须得是数组才能给构造函数传参,
//也许可以传字符串吧,有时间我再试试
$this->layout = 'layouts' . DIRECTORY_SEPARATOR . $params[0];
}
function view($view, $data = null, $flag = false) {
$ci = &get_instance();
$data['content'] = $ci->load->view($view, $data, true);
//这里的第三个参数true代表不输出,如果是false就会输出,默认是false,
//和thinkphp里的display和assign类似,这里用第三个参数来控制
if ($flag) {
$view = $ci->load->view($this->layout, $data, true);
return $view;
} else {
$ci->load->view($this->layout, $data, false);
}
}
}
?>
5,在登陆成功进入后台后,在公共类MY_Controller,该类的构造方法中,进行权限检查,layout加载,根据不同角色生成不同菜单等等,然后再定义不同的controller去继承该公共类。
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $_data = [];
function __construct() {
parent::__construct();
$this->load->model('user');
$this->load->helper('url');
$this->load->library('Layout', array('main'));
if (!$this->user->is_logged_in()) {
redirect('Login');
}
}
function pagenation(){
}
}
6,具体实现可以参考上传代码以及数据库文件