I have the following.
controllers/customers.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 customers extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function view($id) {
$this->load->model('customers');
$news = $this->customers->view_customer($id);
$data['title'] = $news['title'];
$data['body'] = $news['body'];
$this->load->view('customers_customer_view', $data);
}
function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('customers_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('dashboard', 'refresh');
}
}
?>
models/customer.php
<?php
class customers_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function view_customer($id) {
if($id != FALSE) {
$query = $this->db->get_where('news', array('id' => $id));
return $query->row_array();
}
else {
return FALSE;
}
}
}
?>
views/customers_customer_view.php
<?php print $title; ?>
<?php print $body; ?>
I am very new to code igniter, I have followed this tutorial from the web, No matter what i do i cannot get the database info to display when loading root/customers/view/1
All i get is a blank page. Even if i change the view to include a some static text it wont display, From this i believe it to be something wrong with loading the view, But all looks ok to me.
Please can somebody assist.
You wrote:
$this->load->model('customers');
But model file is named: customer.php.
And class name is: customers_model.
Please check it again.
I will give you an example:
$this->load->model('customers');
Your model file have to be: customers.php.
And your class name have to be: class Customers {}
Related
Hi Everyone i asking if how i can resolved this kind of problem. the problem is when i clicked the back button after logging out the user can still access the page or by typing the link of the page. i thought if i can destroy the session it will automatically disabled those pages..
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends MY_Controller {
public function index(){
$this->data['page_title'] = "User Login";
$this->load->view('templates/master', $this->data);
}
public function login(){
$username = $_POST['username'];
$password = $_POST['password'];
$data = $this->User_model->login ($username, $password);
if($data){
$this->session->set_userdata('users', $data);
$session_data = array(
'username' => $username);
$this->session->set_userdata($session_data);
redirect('users');
}
else{
$this->session->set_flashdata
('loginfail','<div class="alert alert-danger">×
<strong>Danger !</strong> Invalid Email or Password .</div>');
return redirect("auth");
}
}
public function logout()
{
$this->session->unset_userdata(array('username','id'));
$this->session->sess_destroy();
redirect('auth');
}
}
<a href="<?php echo ('auth/logout')?>" data-toggle="modal" data-target="#logoutModal">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Logout
</a>
My Homepage controller Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends MY_Controller {
function __construct() {
if(empty($this->session->userdata('id'))){
redirect('auth/logout');
}
}
public function index()
{
$this->data['page_title'] = "Users List";
$this->data['users'] = $this->User_model->get();
$this->load->view('templates/master', $this->data);
}
public function add()
{
$this->data['page_title'] = "Add User";
$input_data = $this->input->post();
if(!empty($input_data))
{
$this->User_model->insert($input_data);
redirect('/users');
} else {
$this->load->view('templates/master', $this->data);
}
}
public function edit($id)
{
$this->data['page_title'] = "Edit User";
$input_data = $this->input->post();
if(!empty($input_data)){
$this->User_model->update($input_data);
redirect('/users');
} else {
$this->data['users'] = $this->User_model->get($id);
$this->load->view('templates/master', $this->data);
}
}
public function delete($id)
{
$this->User_model->delete($id);
redirect('/users');
}
}
My Core Controller Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $data;
public function __construct()
{
parent::__construct();
define('CONTROLLER', $this->router->fetch_class());
define('METHOD', $this->router->fetch_method());
}
}
Yes, you must log out of the user session. And you have to check the user session in the constructor of a controller.
Example:
class Users extends MY_Controller {
function __construct() {
if(empty($this->session->userdata())){
redirect('LOGIN_CONTROLLER');
}
}
}
logout and login works fine...
but you have to restrict or privilege your functions
example
public function isLoggedIn() {
if ($this->session->userdata('uId') == TRUE) {
return true;
} else {
return false;
}
}
public function index() {
$status = $this->session->userdata('uStatus');
if ($this->isLoggedIn() == TRUE && $status == "1") {
//your code here
} else {
$this->session->set_flashdata('error', 'You have to login first');
redirect('login');
}
}
You should redirect
if(empty($this->session->userdata('id'))){
redirect('LOGIN_CONTROLLER/METHOD_NAME_HERE');
}
i have a problem, i have login page, it will direct to the profile if we input the correct email & password, but the problem is when i change the url to the login, it still move to the login page, how can i block the login page if I'm already logged in so that will be dirrect to the profile although the url i change to the login page it's still direct to the profile page.
below is the code :
class Profile extends CI_Controller {
public function index()
{
if($this->session->userdata('logged_in')){
$session_data = $this->session->userdata('logged_in');
$data['email'] = $session_data['email'];
$this->load->view('view_profile', $data);
}else{
redirect('login','refresh');
}
}
public function logout(){
$this->session->unset_userdata('logged_in');
$this->session->sess_destroy();
redirect(site_url('home'),'refresh');
}
}
this is the userdata('logged_in')
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
$this->form_validation->set_rules('email','Email','trim|required');
$this->form_validation->set_rules('password','Password','trim|required|callback_basisdata_cek');
if($this->form_validation->run()==false){
$this->load->view('view_home');
}else{
redirect(base_url('index.php/profile'),'refresh');
}
}
function basisdata_cek($password){
$email = $this->input->post('email');
$result = $this->login->login($email,$password);
if($result){
$sess_array = array();
foreach($result as $row){
$sess_array = $arrayName = array('email'=>$row->email, 'password'=>$row->password);
$this->session->set_userdata('logged_in',$sess_array);
}
return true;
}else{
$this->session->set_flashdata('basisdata_cek', 'Invalid email or password');
redirect(base_url('index.php/login'),'refresh');
return false;
}
}
}
BEST Practice
Always create User / Login Controller separate, you will have more space to create functionalities like user role check and redirecting the user to their role specific dashboards / profiles.
Keep Login / Logout check functions in a parent controller and extend your controller from that controller. For example, create a controller named My_Controller and put your isLoggedin check and logout functions in it.
class My_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function isLoggedIn()
{
if(!empty($this->session->userdata['id'])&& $this->session->userdata['type']=='admin')
{
return true;
}
else
{
return false;
}
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url());
}
}
Then create your user or login controller to render the login page and implementing login functionality
class Login extends My_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
$this->load->library("security");
}
public function index()
{
if(!$this->isLoggedin()) // if the user is not logged in render login screen
{
if($_POST) // or if($this->input->post)
{
$data=$this->security->xss_clean($_POST);
$user=$this->user_model->checkUser($data);
if(!empty($user))
{
$this->session->set_userdata($user);
redirect(base_url().'profile');
}
else
{
$data['errors']='Wrong Credentials';
$this->load->view('login',$data);
}
}
else
{
$this->load->view('login');
}
}
else // but if the user is logged in , take him to profile.
{
redirect(base_url().'profile');
}
}
And in your profile Controller
class Profile extends My_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function index()
{
// if user is not logged in , redirect him back to login screen.
if(!$this->isLoggedin()){ redirect(base_url().'login');}
$userId=$this->session->userdata['id']; // this index depends on the field name
$data['user']=$this->user_model->getUserDataById($userId);
$this->load->view('profile',$data);
}
}
this is the model
<?php
Class Clase_model extends CI_Model
{
function __construct(){
parent::__construct();
}
function getAll(){
$query = $this-> db ->get("clase");
if($query -> num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
}
?>
and this is the controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Clase extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('clase_model','',TRUE);
}
function index()
{
if($this->session->userdata('logged_in')){
$data['clases'] = $this->clase_model->getAll();
//$this->load->view('header', $data);
//$this->load->view('clase_view', $data);
print_r ($data['clases']);
}
else{
redirect('login', 'refresh');
}
}
}
?>
The connexion with the database is correct because another model is working correct ,but in this when I try to print the result of the query it's empty but the table it's not empty,it's something wrong??
Can you try this:
<?php
Class Clase_model extends CI_Model
{
function __construct(){
parent::__construct();
}
function getAll(){
$query = $this-> db ->get("clase");
if($query -> num_rows() == 1)
{
return $query->result_array();
}
else
{
return false;
}
}
}
?>
your model is working for me... i think it's not load properly at your end.
can you try this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Clase extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('clase_model');
}
function index()
{
if($this->session->userdata('logged_in')){
$data['clases'] = $this->clase_model->getAll();
echo $this->db->last_query();
print_r ($data['clases']);
}
else{
redirect('login', 'refresh');
}
}
}
?>
First off, heres my code:
<?php
class Admin extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('admin_model');
}
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home', 'refresh');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
if ($session_data['id'] != 1){
$this->load->view('head');
echo "Sorry, you have to be an administrator to access this page";
$this->load->view('footer');
} else {
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('head');
$this->load->model('admin_model');
$data['users'] = $this->admin_model->show_data();
$data['bikes'] = $this->admin_model->show_bikes();
$this->load->view('admin', $data);
$this->load->view('footer');
}
} else
{
redirect('login', 'refresh');
}
}
The dilemma I'm in is, yes this will stop all normal users accessing the admin/index page. However they still will be able to access admin/create, admin/update and so on unless i put an if statement on all the functions which will take some time. Is there a quicker way (possibly something i could put in the construct) that will apply the check to all the admin pages? Thanks
Simply move your admin-check code to the constructor:
<?php
class Admin extends CI_Controller {
public function __construct()
{
parent::__construct();
if(!$this->session->userdata('logged_in')) {
redirect('login', 'refresh');
}
if ($session_data['id'] != 1){
$this->load->view('head');
echo "Sorry, you have to be an administrator to access this page";
$this->load->view('footer');
exit; // or return? sorry, not too familiar w/ CodeIgniter
}
$this->load->model('admin_model');
}
...
public function index()
{
...
}
This is my Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class admin extends ci_controller{
function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->helper(array('form', 'url', 'security', 'html'));
$this->load->library('form_validation');
$this->load->model($this->config->item('admin_model'), 'admin_db_connection', TRUE);
//$this->load->model('admin_model' ,TRUE);
//$this->load->helper('security');
$this->load->helper('date');
//$this->load->library('Ajax');
$this->load->library("pagination");
$this->load->database();
$this->load->helper('url'); //You should autoload this one ;)
}
public function index(){
$this->load->view('admin/login');
}
public function check_admin(){ //echo'admin';
$this->load->helper('form');
$this->form_validation->set_rules('admin_name','admin name','trim|required|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|xss_clean');
$this->form_validation->set_rules('password','password','trim|required|xss_clean');
if($this->form_validation->run()== FALSE)
{ //echo 'invalid login ';
$this->index();
}
else
{
$data=array();
$data['admin_name']=$this->input->post('admin_name',true);
$data['email']=$this->input->post('email',true);
$data['password']=$this->input->post('password',true);
//echo "<pre>";
if ($query = $this->admin_db_connection->check_admin_validation($data))
{
// print_r($po);exit;
$newdata=array
(
'id' => $query[0]['id'],
'admin_name' => $query[0]['admin_name'],
'email'=>$query[0]['email'],
'status' => $query[0]['status'],
'sign_in'=>TRUE
);
// echo "<pre>";
//print_r($newdata);exit;
$this->session->set_userdata('auth', $newdata);
//$return= true;
//print_r($auth);exit;
redirect('dashboard');
return TRUE;
}
else
{
echo 'invalid login';
$this->index();
//redirect('admin/index', 'refresh');
return FALSE;
}
}
}
function logout()
{
$this->session->sess_destroy();
redirect('admin');
}
}
?>
This is my model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class admin_model extends ci_model{
function check_admin_validation($data){
$this->session->userdata('auth');
$this->db->select('*');
$this->db->from('admin_user');
$this->db->where('admin_name' , $data['admin_name']);
$this->db->where('email', $data['email']);
$this->db->where('password', $data['password']);
$query=$this->db->get();
if($query->num_rows()>0)
{
$resulet=$query->result_array();
$query->free_result();
return $resulet;
}
else
{
return false;
}
}
}
?>
When I use this code $this->session->set_userdata($newdata); instead of $this->session->set_userdata('auth', $newdata); then it works, but above code doesn't. Can someone tell me, where the problem is?
If I am not mistaken, the second parameter for the set_userdata function is a string, whereas you're passing an array.
This may be why your code isn't working.
The way to set session value at codeigniter is
$this->session->set_userdata('some_name', 'some_value');
//some_value should not be array
//But your are setting array as value which is wrong.
$this->session->set_userdata($newdata);
//This will set each array key to your session.
//That's why it is working
If you really want to set array into one sesson key you can do it following way
$this->session->set_userdata("auth",json_encode($newdata);
Now you can retrive data as
$auth=json_decode($this->session->userdata("auth"));
please look at codeigniter documentation
thank you now i solved my problem.thank you all and stackoverflow because if i not post here i cant find my answer.here is the problem my dashboard i passed wrong value 'sing_in' right value 'auth'.
if (!$this->session->userdata('sing_in'))
{
redirect('admin');
}`enter code here`