Why do all my pages go to the same controller in CodeIgniter? - php

When I load up my homepage, it works perfectly. The custom helper I made for the CSS and JS files is working and it loads through the correct controller/view.
Every other page, however, loads from a the wrong controller (the News Controller). And the controller isn't using the custom helper for whatever reason, so there's no style on the page.
Here's what I have in my routes.php and each of my controllers:
route.php
$route['translate_uri_dashes'] = FALSE;
$route['news'] = 'news/index/1';
$route['news/create'] = 'news/create';
$route['news/view'] = 'news/index/1';
$route['news/view/(:any)'] = 'news/view/$1';
$route['news/(:any)'] = 'news/index/$1';
$route['logout'] = 'login/logout';
$route['register'] = 'login/register';
$route['confirm/(:any)/(:any)'] = 'login/confirm/$1/$2';
$route['default_controller'] = 'index';
$route['404_override'] = 'error';
Index Controller
<?php
class Index extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->library('session');
$data['page'] = 'Home';
$data['section'] = 'None';
if (isset($_SESSION['id'])) {
$data['user'] = $this->user_model->get_user($_SESSION['id']);
}
$this->load->view('layout/header', $data);
$this->load->view('layout/breadcrumb', $data);
$this->load->view('layout/body');
$this->load->view('index');
$this->load->view('layout/close');
$this->load->view('layout/footer');
}
}
News Controller
<?php
class News extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('news_model');
$this->load->library('session');
}
public function index($page) {
$data['page'] = 'News';
$data['section'] = 'None';
if (isset($_SESSION['id'])) {
$data['user'] = $this->user_model->get_user($_SESSION['id']);
}
$data['news'] = $this->news_model->get_news(NULL, $page);
$data['pageNo'] = $page;
$data['entries'] = $this->news_model->get_total();
$this->load->view('layout/header', $data);
$this->load->view('layout/breadcrumb', $data);
$this->load->view('layout/body');
$this->load->view('news/index', $data);
$this->load->view('layout/close');
$this->load->view('layout/footer');
}
public function view($id) {
$data['page'] = 'News';
if (isset($_SESSION['id'])) {
$data['user'] = $this->user_model->get_user($_SESSION['id']);
}
$data['news'] = $this->news_model->get_news($id);
$data['section'] = $data['news']['title'];
$data['prev'] = $this->news_model->get_prev($data['news']['pubDate']);
$data['next'] = $this->news_model->get_next($data['news']['pubDate']);
$data['pub'] = $this->user_model->get_user($data['news']['publisher']);
$this->load->view('layout/header', $data);
$this->load->view('layout/breadcrumb', $data);
$this->load->view('layout/body');
$this->load->view('news/view', $data);
$this->load->view('layout/close');
$this->load->view('layout/footer');
}
public function create() {
$this->news_model->set_news();
$this->session->set_userdata('created', 1);
redirect('news');
}
}
Login Controller
<?php
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
}
public function index() {
$this->load->helper('form');
$this->load->library('form_validation');
$data['page'] = 'Login';
$data['section'] = 'None';
if (isset($_SESSION['id'])) {
redirect('/');
} else {
$this->form_validation->set_rules('username', 'Username', 'required', array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('password', 'Password', 'required', array('required' => 'You must provide a %s.'));
if ($this->form_validation->run() !== FALSE) {
$user = $this->user_model->login();
if ($user) {
$this->session->set_userdata('id', $user['id']);
redirect('/');
} else {
$this->session->set_userdata('loginerr', 1);
}
}
$this->load->view('layout/header', $data);
$this->load->view('layout/breadcrumb', $data);
$this->load->view('layout/body');
$this->load->view('login');
$this->load->view('layout/close');
$this->load->view('layout/footer');
}
}
public function logout() {
$this->session->sess_destroy();
redirect('/');
}
public function register() {
$this->load->helper('form');
$this->load->library('form_validation');
$data['page'] = 'Register';
$data['section'] = 'None';
if (isset($_SESSION['id'])) {
redirect('/');
} else {
$this->form_validation->set_rules('username', 'Username', 'required', array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('email', 'Email', 'required', array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('password', 'Password', 'required', array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('confpass', 'Confirm Password', 'required', array('required' => 'You must provide a %s.'));
if ($this->form_validation->run() !== FALSE) {
$this->user_model->register();
if (isset($_SESSION['regerror'])) {
if ($_SESSION['regerror'] == 1) {
$data['error'] = 'Username is already in use.';
} else if ($_SESSION['regerror'] == 2) {
$data['error'] = 'Email Address is already in use.';
} else if ($_SESSION['regerror'] == 3) {
$data['error'] = 'Passwords do not match';
} else {
$data['error'] = 'This IP Address has been banned for the following reason: ' . $_SESSION['regerror'];
}
unset($_SESSION['regerror']);
} else if (isset($_SESSION['register'])) {
$data['success'] = 1;
unset($_SESSION['register']);
}
}
$this->load->view('layout/header', $data);
$this->load->view('layout/breadcrumb', $data);
$this->load->view('layout/body');
$this->load->view('register', $data);
$this->load->view('layout/close');
$this->load->view('layout/footer');
}
}
public function confirm($un = NULL, $conf = NULL) {
$data['page'] = 'Confirmation';
$data['section'] = 'None';
if (isset($_SESSION['id'])) {
redirect('/');
} else {
if ($un == NULL || $conf == NULL) {
$data['message'] = 'No account selected...';
} else {
$check = $this->user_model->confirm($un, $conf);
if ($check == 1) {
$data['message'] = 'Invalid information provided...';
} else if ($check == 2) {
$data['message'] = 'User already confirmed...';
} else {
$data['message'] = 'Your account has been activated! You may now Login!';
}
}
$this->load->view('layout/header', $data);
$this->load->view('layout/breadcrumb', $data);
$this->load->view('layout/body');
$this->load->view('confirm', $data);
$this->load->view('layout/close');
$this->load->view('layout/footer');
}
}
}
Errors Controller
<?php
class Error extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
}
public function index() {
$data['page'] = 'Error 404';
$data['section'] = 'None';
if (isset($_SESSION['id'])) {
$data['user'] = $this->user_model->get_user($_SESSION['id']);
}
$this->output->set_status_header('404');
$this->load->view('layout/header', $data);
$this->load->view('layout/breadcrumb', $data);
$this->load->view('layout/body');
$this->load->view('404');
$this->load->view('layout/close');
$this->load->view('layout/footer');
}
}
Can anyone tell me why this is happening?

['default_controller'] should ALWAYS be at the bottom, this is the LAST point of contact for the routes.
Any custom routes should be above it, also
news/(:any) will overwrite the other news ones, it should be below news/view and news/create
e.g:
$route['translate_uri_dashes'] = FALSE;
$route['news'] = 'news/index/1';
$route['news/create'] = 'news/create';
$route['news/view'] = 'news/index/1';
$route['news/view/(:any)'] = 'news/view/$1';
$route['news/(:any)'] = 'news/index/$1';
$route['logout'] = 'login/logout';
$route['register'] = 'login/register';
$route['confirm/(:any)/(:any)'] = 'login/confirm/$1/$2';
$route['default_controller'] = 'index';
$route['404_override'] = 'error';

Related

Session is not set after redirect in codeigniter

I've created a project in Codeigniter. My problem is when I log in, auth controller shows the value that is set in session $this->session->userdata("logged_in") but it is not redirecting to dashboard.
I also changed the PHP version on the live server from PHP 7.1 to PHP 5.6 but it's still not working. Session works perfectly on local server with xampp but not working on live server
Auth_model
public function Authentification() {
$notif = array();
$email = $this->input->post('email',TRUE);
$password = Utils::hash('sha1', $this->input->post('password'), AUTH_SALT);
$this->db->select('*');
$this->db->from('users');
$this->db->where('email', $email);
$this->db->where('password', $password);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
$row = $query->row();
if ($row->is_active != 1) {
$notif['message'] = 'Your account is disabled !';
$notif['type'] = 'warning';
} else {
$sess_data = array(
'users_id' => $row->users_id,
'first_name' => $row->first_name,
'email' => $row->email
);
$this->session->set_userdata('logged_in', $sess_data);
}
} else {
$notif['message'] = 'Username or password incorrect !';
$notif['type'] = 'danger';
}
return $notif;
}
Auth controller
class Auth extends CI_Controller {
function __construct() {
parent::__construct();
Utils::no_cache();
if ($this->session->userdata('logged_in')) {
redirect(base_url('dashboard'));
exit;
}
}
public function index() {
redirect(base_url('home'));
}
public function login() {
$data['title'] = 'Login';
$this->load->model('auth_model');
if (count($_POST)) {
$this->load->helper('security');
$this->form_validation->set_rules('email', 'Email address', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == false) {
// $data['notif']['message'] = validation_errors();
// $data['notif']['type'] = 'danger';
$status = validation_errors();
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
}
else {
$data['notif'] = $this->auth_model->Authentification();
// it show the result here but not redirect to dashboard
// print_r($this->session->userdata("logged_in"));
// die("auth/login");
}
}
if ($this->session->userdata('logged_in')) {
redirect(base_url('dashboard'));
exit;
}
/*
* Load view
*/
$this->load->view('includes/header', $data);
$this->load->view('home/index');
$this->load->view('includes/footer');
}
dashboard
class Dashboard extends CI_Controller {
var $session_user;
function __construct() {
parent::__construct();
$this->load->model('auth_model');
$this->load->helper('tool_helper');
Utils::no_cache();
if (!$this->session->userdata('logged_in')) {
redirect(base_url('home'));
exit;
}
$this->session_user = $this->session->userdata('logged_in');
}
/*
*
*/
public function index() {
$data['title'] = 'Dashboard';
$data['session_user'] = $this->session_user;
// print_r($this->session->userdata("logged_in")); //its show empty
$data['items'] = $this->auth_model->get_all_products();
$this->load->view('includes/header', $data);
// $this->load->view('includes/navbar');
$this->load->view('includes/navbar_new');
$this->load->view('dashboard/index');
$this->load->view('includes/footer');
}
I don't know why session not set. I have been stuck in this for a week. Please help me out.
Try this.
Change $config['sess_save_path'] = sys_get_temp_dir(); to $config['sess_save_path'] = FCPATH . 'application/cache/sessions/'; in config.php

Unable to do a login redirect in codeigniter

I am trying to develop a login panel using codeigniter but I am unable to do so as I believe my concept is not so clear yet though or Am i doing something wrong please help me out with this concern
Controllers>admin.php
class admin extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('verify_user');
}
public function verify() {
$this->load->library('form_validation');
$username = $this->form_validation->set_rules('username', '', 'required|trim');
$password = $this->form_validation->set_rules('password', '', 'required|trim');
if($this->form_validation->run()) {
$this->verify_user->can_log_in();
redirect('admin/dashboard');
} else {
$this->load->view('admin/login');
}
}
public function dashboard() {
if($this->session->userdata('is_logged_id') == true) {
$this->load->view('admin/dashboard');
} else {
redirect('admin/login');
}
}
models>verify_users.php
class verify_user extends CI_Model {
public function __construct() {
parent::__construct();
}
public function can_log_in() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('users');
$query2 = $this->db->get_where('users', array(
'username' => $this->input->post('username')
));
if($query2->num_rows() == 1) {
$name = $query2->row()->first_name . " " . $query2->row()->last_name;
}
if($query->num_rows() == 1) {
$query = $this->db->get_where('users', array(
'username' => $this->input->post('username')
));
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => 1
);
$this->session->set_userdata('name', $name);
$this->session->set_userdata($data);
return true;
} else {
$data['message'] = 'Incorrect username/password';
$this->load->view('admin/login', $data);
}
}
}
The thing is happening when I login with correct username and password it redirects me back to login.php when I put the model script within the verify function it runs perfectly
Please help me out with this
This is the closest possible fix to your way of implementation.
You need to consider reading more about MVC.
Try replace your controller with this:
class admin extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('verify_user');
}
public function verify() {
$this->load->library('form_validation');
$username = $this->form_validation->set_rules('username', '', 'required|trim');
$password = $this->form_validation->set_rules('password', '', 'required|trim');
if($this->form_validation->run() && $this->verify_user->can_log_in()) {
redirect('admin/dashboard');
} else {
$this->load->view('admin/login');
}
}
public function dashboard() {
if($this->session->userdata('is_logged_in') == "1") {
$this->load->view('admin/dashboard');
} else {
redirect('admin/login');
}
}
}
And your model with this:
class verify_user extends CI_Model {
public function __construct() {
parent::__construct();
}
public function can_log_in() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('users');
$query2 = $this->db->get_where('users', array(
'username' => $this->input->post('username')
));
if($query2->num_rows() == 1) {
$name = $query2->row()->first_name . " " . $query2->row()->last_name;
}
if($query->num_rows() == 1) {
$query = $this->db->get_where('users', array(
'username' => $this->input->post('username')
));
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => "1"
);
$this->session->set_userdata('name', $name);
$this->session->set_userdata($data);
return true;
} else {
$data['message'] = 'Incorrect username/password';
return false;
}
}
}
Check this
class admin extends CI_Controller {
^// this should be Admin
IN model
else {
//$data['message'] = 'Incorrect username/password';
//$this->load->view('admin/login', $data);
//dont load view in model
return false;
}
In controller
if($this->form_validation->run()) {
$res = $this->verify_user->can_log_in();
if($res)
redirect('admin/dashboard');
else
redirect('admin/login');
} else {
$this->load->view('admin/login');
}
Fixing these 3 errors should help you.

Codeiginter Session Issue

i have a problem in a session
ihave made a login page called"alogin"
<?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.
*/
class alogin extends CI_Controller{
public function __construct() {
parent::__construct();
$this->load->model('user_model');
$this->load->model('admin_model');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('articles_model');
$this->load->helper(array('form', 'url'));
}
function index(){
$this->form_validation->set_rules('username',' اسم المستخدم','trim|required|xxs_clean');
$this->form_validation->set_rules('password','كلمة المرور','trim|required|xss_clean');
$this->form_validation->run();
//post value
$data['username'] = $this->input->post('username');
$data['password'] = $this->input->post('password');
if($this->input->post('login')){
if($this->user_model->login($data)){
$this->setsession();
redirect('admin/index');
} else {
redirect('admin');
}
}
$this->load->view('admin/login');
}
public function setsession(){
$dat = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'loggedIn' => TRUE
);
$this->session->set_userdata($dat);
}
public function logout(){
if($this->session->sess_destroy()){
redirect('admin/alogin');
} else {
// redirect('admin/log/index');
}
}
}
and make the admin pages in controller file called"admin"
and this is the code
<?php
class admin extends CI_Controller
{
public function __construct() {
parent::__construct();
$this->load->model('user_model');
$this->load->model('admin_model');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('articles_model');
$this->load->helper(array('form', 'url'));
if(!$this->session->userdata('loggedIn')){
redirect('alogin');
}
}
public function index(){
$data['count'] = $this->admin_model->count_message();
$data['messages'] = $this->admin_model->show_message();
$data['title'] = ' لوحة التحكم';
$data['subview'] = 'admin/main';
$this->load->view('admin/index',$data);
}
public function setting(){
$data['settings']= $this->admin_model->settings();
$data['title'] = ' تعديل اعدادات الموقع';
$data['subview'] = 'admin/setting';
$this->load->view('admin/index',$data);
}
public function set_update(){
$data = array(
'site_name' => $this->input->post('site_name'),
'site_desc'=> $this->input->post('site_desc')
);
$update = $this->admin_model->set_update($data);
if(isset($update)){
redirect('admin/setting');
}
}
function message(){
$data['messages'] = $this->admin_model->show_message();
$data['title'] = 'الرسائل';
$data['subview'] = 'admin/message';
$this->load->view('admin/index',$data);
}
/// articles
public function add_article(){
//
// do upload
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$config['max_width'] = 1024;
$config['max_height'] = 1000;
$this->load->library('upload', $config);
if(!$this->upload->do_upload('file')){
$data['error'] = $this->upload->display_errors();
} else {
$data['img_data'] = $this->upload->data();
$img = $this->upload->data();
}
$articels = array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'date' => date("Y-m-d H:i:s") ,
'img' => #$img['full_path'],
);
if($this->input->post('add')){
//form validation
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('author','title','required');
$this->form_validation->set_rules('content','title','required');
$this->form_validation->set_rules('img','title','required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/add_c');
}
else
{
$this->load->view('admin');
}
//form validation
if($this->articles_model->add_article($articels)){
$data['message'] = 'تم اضافة الخبر بنجاح';
}
} else {
echo 'problem';
}
$data['title'] = 'اضافة خبر';
$data['subview'] = 'admin/add_c';
$this->load->view('admin/index',$data);
}
public function articles(){
$data['articels'] = $this->articles_model->get_articles();
$data['title'] = 'عرض المقالات';
$data['subview'] = 'admin/articles';
$this->load->view('admin/index',$data);
}
function delete_articels($id){
$id = $this->uri->segment(4);
if( $this->articles_model->delete_articles($id)){
redirect('admin/articles');
}
}
function edit_articels(){
$id = $this->uri->segment(3);
$data['articels'] = $this->articles_model->get_article_id($id);
$artc = array(
'title' => $this->input->post('title'),
'author' => $this->input->post('author'),
'content' => $this->input->post('content'),
'img' => $this->input->post('img')
);
if($this->input->post('update')){
if($this->articles_model->edit_c($id,$artc)){
echo 'تم تعديل المقال بنجاح';
} else {
echo 'مشكلة فى تعديل البيانات';
}
}
$data['title'] = 'تعديل المقال';
$data['subview'] = 'edit_c';
$this->load->view('admin/index',$data);
}
public function stat(){
$data['stats']= $this->admin_model->get_static();
$data['subview'] = 'admin/stat';
$data['title'] = 'تعديل احصائيات العيادة';
$this->load->view('admin/index',$data);
}
// pat
function add_pat(){
$pats = array(
'pat_name' => $this->input->post('pat_name'),
'pat_pat' => $this->input->post('pat_pat'),
'pat_content'=> $this->input->post('pat_content')
);
if($this->input->post('add')){
$this->admin_model->add_pat($pats);
}
$data['subview'] = 'admin/add_pat';
$data['title'] ='اضافة حالة جديدة';
$this->load->view('admin/index',$data);
}
function show_pats(){
$data['title'] = 'عرض الحالات ';
$data['pats'] = $this->admin_model->show_pat();
$data['subview'] = 'admin/show_pats';
$this->load->view('admin/index',$data);
}
function delete_pat(){
$id = $this->uri->segment(3);
if($this->admin_model->delete_pat($id)){
redirect('admin/show_pats');
}
}
function edit_pat(){
$id = $this->uri->segment(3);
$pat = array(
'pat_name' => $this->input->post('pat_name'),
'pat_pat' => $this->input->post('pat_pat'),
'pat_content' => $this->input->post('pat_content')
);
if($this->input->post('update')){
if($this->admin_model->edit_pat($id,$pat)){
redirect('admin/show_pats');
echo 'done';
} else {
redirect('home');
}
}
$data['title'] = 'تعديل';
$data['pats'] = $this->admin_model->show_pat_id($id);
$data['subview'] = 'admin/edit_pat';
$this->load->view('admin/index',$data);
}
/// videos
function show_videos(){
$data['videos']= $this->admin_model->get_videos();
$data['title'] = 'عرض الفديوهات';
$data['subview'] ='admin/show_videos';
$this->load->view('admin/index',$data);
}
function add_video(){
$add = array(
'video_title' => $this->input->post('video_title'),
'video_url' => $this->input->post('video_url')
);
if($this->input->post('add')){
$this->admin_model->add_video($add);
redirect('admin/show_videos');
}
$data['title'] = 'اضف فديو جديد ';
$data['subview'] = 'admin/add_video';
$this->load->view('admin/index',$data);
}
function edit_video(){
$id = $this->uri->segment(3);
$data['videos'] = $this->admin_model->get_video_id($id);
$data['id'] = $id;
$edit = array(
'video_title' => $this->input->post('video_title'),
'video_url'=> $this->input->post('video_url')
);
if($this->input->post('update')){
$this->admin_model->edit_video($id,$edit);
redirect('admin/show_videos');
} else {
echo 'problem';
}
$data['title'] = 'تعديل الفديو';
$data['subview'] = 'admin/edit_video';
$this->load->view('admin/index',$data);
}
function delete_video(){
$id = $this->uri->segment(3);
if($this->admin_model->delete_video($id)){
redirect('admin/show_videos');
}
}
}
the page is login successfuly but if i refresh or go to any inner admin page
redirect to login page ???
Array
(
[__ci_last_regenerate] => 1442853634
[username] => nader
[password] => 01147187698
[loggedIn] => 1
)
and the problem is when i refresh the index page or enter any page redirect to alogin(login page)
Try on your admin controller
public function __construct() {
parent::__construct();
if($this->session->userdata('loggedIn') == FALSE){
redirect('alogin');
}
$this->load->model('user_model');
$this->load->model('admin_model');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('articles_model');
$this->load->helper(array('form', 'url'));
}
And change on your session check ! to FALSE and move it to the top like shown
Also try and var dump sessions just to make sure working.
echo '<pre>';
echo print_r($this->session->all_userdata());
echo '</pre>';
just check the user session in constructor of each controller
in your controller where you are saving session ..?
first of all make a method in base/parent controller to check the user is login
then call it in each controller's constructor
you can check all stored session through below given method
$this->session->all_userdata();

Codeigniter login system with session to redirect user to page if password correct

I created a login system but every time I setup an if statement it loops back to the login page when I enter correct password. I need the index function in the controller, the list_employee function and View_employee function to redirect user to login page if they access it directly but if they enter correct password allow them to go to it.
user_authentication controller
<?php
session_start(); //we need to start session in order to access it through CI
Class User_Authentication extends CI_Controller {
public function __construct() {
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
// Load database
$this->load->model('login_database');
}
// Show login page
public function user_login_show() {
$this->load->view('login_form');
}
// Show registration page
public function user_registration_show() {
$this->load->view('registration_form');
}
// Validate and store registration data in database
public function new_user_registration() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('email_value', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('registration_form');
} else {
$data = array(
'name' => $this->input->post('name'),
'user_name' => $this->input->post('username'),
'user_email' => $this->input->post('email_value'),
'user_password' => $this->input->post('password')
);
$result = $this->login_database->registration_insert($data) ;
if ($result == TRUE) {
$data['message_display'] = 'Registration Successfully !';
$this->load->view('login_form', $data);
} else {
$data['message_display'] = 'Username already exist!';
$this->load->view('registration_form', $data);
}
}
}
// Check for user login process
public function user_login_process() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->login_database->login($data);
if($result == TRUE){
$sess_array = array(
'username' => $this->input->post('username')
);
// Add user data in session
$this->session->set_userdata('logged_in', $sess_array);
$result = $this->login_database->read_user_information($sess_array);
if($result != false){
$data = array(
'name' =>$result[0]->name,
'username' =>$result[0]->user_name,
'email' =>$result[0]->user_email,
'password' =>$result[0]->user_password
);
redirect('employee');
}
}else{
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('login_form', $data);
}
}
}
// Logout from admin page
public function logout() {
// Removing session data
$sess_array = array(
'username' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
$data['message_display'] = 'Successfully Logout';
$this->load->view('login_form', $data);
}
}
?>
employee controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Employee extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('login/employee_model');
}
//Shows the dashboard
public function index()
{
$this->load->view('header');
$this->load->view('employee');
$this->load->view('login/footer');
}
//Insert the employee
public function insert_employee()
{
$data=array('name'=>$this->input->post('name'),
'LanId'=>$this->input->post('LanId'),
'reason'=>$this->input->post('reason'),
'PepNumber'=>$this->input->post('PepNumber'),
'Employee_Number'=>$this->input->post('Employee_Number'),
'department'=>$this->input->post('department'),
'status'=>1);
//print_r($data);
$result=$this->employee_model->insert_employee($data);
if($result==true)
{
$this->session->set_flashdata('msg',"Employee Records Added Successfully");
redirect('employee');
}
else
{
$this->session->set_flashdata('msg1',"Employee Records Added Failed");
redirect('employee');
}
}
//List of Employees
public function list_employees()
{
$data['employee']=$this->employee_model->get_employee();
$this->load->view('header');
$this->load->view('list_of_employees',$data);
$this->load->view('login/footer');
}
//List of Employees
public function viewlist_employees()
{
$data['employee']=$this->employee_model->get_employee();
$this->load->view('header');
$this->load->view('viewlist_of_employees',$data);
$this->load->view('login/footer');
}
public function delete_employee()
{
$id=$this->input->post('id');
$data=array('status'=>0);
$result=$this->employee_model->delete_employee($id,$data);
if($result==true)
{
$this->session->set_flashdata('msg1',"Deleted Successfully");
redirect('employee/list_employees');
}
else
{
$this->session->set_flashdata('msg1',"Employee Records Deletion Failed");
redirect('employee/list_employees');
}
}
public function edit_employee()
{
$id=$this->uri->segment(3);
$data['employee']=$this->employee_model->edit_employee($id);
$this->load->view('header',$data);
$this->load->view('edit_employee');
}
public function update_employee()
{
$id=$this->input->post('id');
$data=array('name'=>$this->input->post('name'),
'LanID'=>$this->input->post('LanID'),
'reason'=>$this->input->post('reason'),
'PepNumber'=>$this->input->post('PepNumber'),
'Employee_Number'=>$this->input->post('Employee_Number'),
'department'=>$this->input->post('department'),
'status'=>1);
$result=$this->employee_model->update_employee($data,$id);
if($result==true)
{
$this->session->set_flashdata('msg',"Employee Records Updated Successfully");
redirect('employee/list_employees');
}
else
{
$this->session->set_flashdata('msg1',"No changes Made in Employee Records");
redirect('employee/list_employees');
}
}
}
?>
login_database model
<?php
Class Login_Database extends CI_Model {
// Insert registration data in database
public function registration_insert($data) {
// Query to check whether username already exist or not
$condition = "user_name =" . "'" . $data['user_name'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 0) {
// Query to insert data in database
$this->db->insert('user_login', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
} else {
return false;
}
}
// Read data using username and password
public function login($data) {
$condition = "user_name =" . "'" . $data['username'] . "' AND " . "user_password =" . "'" . $data['password'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
}
// Read data from database to show data in admin page
public function read_user_information($sess_array) {
$condition = "user_name =" . "'" . $sess_array['username'] . "'";
$this->db->select('*');
$this->db->from('user_login');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return false;
}
}
}
?>
employee_model
<?php
class Employee_model extends CI_Model
{
public function insert_employee($data)
{
$this->db->insert('employee_list',$data);
return ($this->db->affected_rows() != 1 ) ? false:true;
}
public function get_employee()
{
$this->db->select('*');
$this->db->from('employee_list');
$this->db->where('status',1);
$query =$this->db->get();
return $query->result();
}
public function delete_employee($id,$data)
{
$this->db->where('id',$id);
$this->db->update('employee_list',$data);
return ($this->db->affected_rows() != 1 ) ? false:true;
}
public function edit_employee($id)
{
$this->db->select('*');
$this->db->from('employee_list');
$this->db->where('id',$id);
$this->db->where('status',1);
$query =$this->db->get();
return $query->result();
}
public function update_employee($data,$id)
{
$this->db->where('id',$id);
$this->db->update('employee_list',$data);
return ($this->db->affected_rows() != 1 ) ? false:true;
}
}
add if statement with logged_in and a redirect to login form if it
is incorrect
public function index()
{
if($this->session->userdata('logged_in'))
{
$this->load->view('header');
$this->load->view('employee');
$this->load->view('login/footer');
}else{
redirect('user_authentication/user_login_show');
}
}
Best Practice is to add the check in the constructor of your controller in CI.
here is the example of mine.
public function __construct() {
parent::__construct();
if (!$this->session->userdata('user_data')) {
return redirect('login');
}
$this->load->model('customer_model');
}
you can add the else statement to redirect to the dashboard or what the resulting page if user is logged in.
Add this line of code to your constructors:
$this->load->library('session');
This will help you.
public function login()
{
$this->load->view('login');
if (isset($_POST['login']))
{
$emailid = $this->input->post('emailid');
$password = $this->input->post('password');
$this->load->model('main_model');
if($this->main_model->can_login('$emailid','$Password'))
{
$session_data = array(
'emailid' => $emailid,
'password' => $password,
'iss_logged_in' => 1
);
$this->session->set_userdata($session_data);
redirect(base_url().'index.php/Hello_cnt/');
}
else
{
$this->session->set_flashdata('error', 'Invalid Username and Password');
redirect(base_url().'index.php/Hello_cnt/login');
}
}
}

Login authentication

I have placed 2 controller login and site1.When i login and enter to members area to view pages and if i copy that url and placed in another tab.it opens.But my aim is to display u have no permission to access the page.
Controller:login
<?php
class Login extends CI_Controller {
function index()
{
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function inactive()
{
echo"<script>alert('In active user Please contact the administrator');</script>";
$this->load->view('login_form');
}
function invalid()
{
echo"<script>alert('Invalid username or password');</script>";
$this->load->view('login_form');
}
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
if($query->num_rows()>0){
$status = $query->row()->account_status;}
else {
$status = ''; }
//Account active
if($status == 'active')
{
$this->session->set_userdata($data);
redirect('site1/members_area');
}
else if ($status == 'inactive')//Account In active
{ $this->inactive();
}
else // incorrect username or password
{
$this->invalid();
}
}
}
function signup()
{
$data['main_content'] = 'signup_form';
$this->load->view('includes/template', $data);
}
function create_member()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('first_name', 'Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('college_name', 'college_name', 'trim|required');
$this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
$this->load->helper('date');
if($this->form_validation->run() == FALSE)
{
$this->load->view('signup_form');
}
else
{
$this->load->model('membership_model');
if($query = $this->membership_model->create_member())
{
$data['main_content'] = 'signup_successful';
$this->load->view('includes/template', $data);
}
else
{
$this->load->view('signup_form');
}
}
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
site1:
<?php
class Site1 extends CI_Controller
{
function members_area()
{
$this->load->view('index');
}
function another_page() // just for sample
{
echo 'good. you\'re logged in.';
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page. Login';
die();
//$this->load->view('login_form');
}
}
}
}
Sessions in PHP are carried over between tabs. The server doesn't really know how to seperate between two tabs. Read the PHP docs on sessions for more information http://us2.php.net/manual/en/intro.session.php

Categories