<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller { //ชื่อ class กับชื่อไฟล์ควรเป็นชื่อเดียวกัน
public function index() {
$this->load->view('login'); //ส่งไปแสดงผลที่ views/login.php
}
public function CheckLogin() {
$this->form_validation->set_rules('username', 'Username', 'required|trim', array('required'=>'กรุณากรอกชื่อผู้ใช้')); //ฟิลด์, label
$this->form_validation->set_rules('password', 'Password', 'required|trim|callback_verifyUser', array('required'=>'กรุณากรอกรหัสผ่าน'));
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if ($this->form_validation->run() == false) {
$this->load->view('login');
}
else {
redirect('Home','refresh');
}
}
public function verifyUser($password) {
$username = $this->input->post('username');
$this->load->model('LoginModel'); // เรียกใช้งาน LoginModel
$result = $this->LoginModel->login($username, $password); //query the database ส่งค่าไปที่ LoginModel
if ($result) {
$sess_array = array();
//if(isset($result) && sizeof($result)>0){
foreach($result as $row){
$sess_array = array(
'username'=>$row->uLogin, // ชื่อsession=>$row->ฟิลด์
'level'=>$row->uLevel
);
$this->session->set_userdata('logged_in', $sess_array); //สร้าง session จากตัวแปร array
}
//}
return true;
}
else {
$this->form_validation->set_message('verifyUser', 'ชื่อผู้ใช้หรือรหัสผ่านผิด! กรุณาลองอีกครั้ง');
return false;
}
}
}
Controller home Code (PHP)
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//session_start(); //we need to call PHP's session object to access it through CI
class Home extends CI_Controller {
public function index() {
if($this->session->userdata('logged_in') == null){
$this->load->view('login');
}
else {
$this->load->view('index');
}
print_r($this->session->userdata('logged_in'));
}
public function sess(){
if($this->session->userdata('logged_in')){
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['level'] = $session_data['level'];
$this->load->view('home', $data);
}
else{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function logout(){
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('login', 'refresh');
}
}
?>
Model Code (PHP)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class LoginModel extends CI_Model
{
public function login($name,$pass)
{
$this->db->select('uLogin','uPassword','uLevel');
$this->db->from('tbl_user');
$this->db->where('uLogin', $name);
$this->db->where('uPassword', md5($pass));
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
}
else {
return false;
}
}
}
?>