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`
Related
Session is not working out when redirecting from one controller to another. In below example, I am simply trying to check login and if valid user then set username to session from the Controller named "Login" and redirect to another controller "Testing" and print the session value. But, When the user is validated, session works fine till we are in Login controller (I checked by putting print_r($this->session->userdata('username')); by removing redirect method) and when I redirect, the session value shows empty from redirected Controller.
Here is the sample of my code:
Controller: Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('M_login');
$this->load->helper('url');
$this->load->library('session');
$this->load->helper('form');
}
public function index()
{
$u=$this->session->userdata('username');
if($u) {
redirect('Testing');
} else {
$this->load->view('login');
}
}
public function login_form()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if($this->form_validation->run()==FALSE)
{
$this->load->view('login');
}
else{
$result = $this->M_login->takeUser();
if(count($result)>0)
{
$user = $this->input->post('username', TRUE);
$this->session->set_userdata('username', $username);
redirect('Testing');
}
else{
?>
<script>
alert('Failed Login: Check your username and password!');
history.go(-1);
</script>
<?php
}
}
}
public function logout()
{
$this->session->sess_destroy();
redirect('login/login_form');
}
}
Model: M_login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_login extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function takeUser()
{
$username = $this->input->post('username');
$password1 = $this->input->post('password');
$password = md5($password1);
$this->db->select('username');
$this->db->from('employee');
$this->db->where('username', $username);
$this->db->where('password', $password);
$result = $this->db->get();
return $result->row_array();
}
}
Controller: Testing.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Testing extends CI_Controller
{
public function __construct(){
parent::__construct();
$this->load->library('session');
}
public function index() {
print_r($this->session->userdata('username'));
}
}
Also I have autoload session:
$autoload['libraries'] = array('database','session','form_validation', 'pagination', 'user_agent','encryption');
The problem is probably in these lines of code from Login.php
$user = $this->input->post('username', TRUE);
$this->session->set_userdata('username', $username);
Notice that the variable $user is set with the value from $_POST['username'], but then contents of $username is stored in the session.
Try this
$user = $this->input->post('username', TRUE);
$this->session->set_userdata('username', $user);
variable $username is not defined in the login_form() function just change
$username = $this->input->post('username', TRUE);
$this->session->set_userdata('username', $username);
or simply with one line
if(count($result)>0)
{
$this->session->set_userdata('username', $this->input->post('username'));
redirect('Testing');
}
it's working I checked.
Right now i am working on localhost for testing of my project.. but when try to login for the first time. it shows nothing means page don't redirect('admin/dashboard');..
But when i try next time.. it works everything fine..
Please anyone can help!!
Thanks in advance.
I am adding a image here. so that you can see what actual the problem was,
This is model file.
<?php
class Admin_model extends CI_Model{
public function login($username,$password){
$enc = md5($password); //for password encryption
$this->db->where('username',$username);
$this->db->where('password',$enc);
$result=$this->db->get('admin');
if($result->num_rows()==1){
return $result->row();
}else{
return false;
}
}
}
This is my controller file.
<?php
class Admin_login extends CI_Controller{
public function __Construct(){
parent::__Construct();
$this->load->model('admin_model','secure_admin_model'); //here i am including model file..
}
public function login(){
$this->form_validation->set_rules('username','Username','trim|required');
$this->form_validation->set_rules('password','Password','trim|required');
if($this->form_validation->run()==FALSE){
$this->load->view('admin/layouts/admin_login');
$this->session->unset_userdata('logged_in');
}
else{
$username=$this->input->post('username');
$password=$this->input->post('password'); // i am using md5 for hashing
$userid=$this->secure_admin_model->login($username,$password);
if($userid){
$user_data=array(
'user_id'=>$userid,
'username'=>$username,
'logged_in'=>true
);
$this->session->set_userdata($user_data);
$this->session->set_flashdata('pass_login','You are logged in'); // Here i am creating session..
redirect('admin/dashboard');
}
else{
$this->session->set_flashdata('wrong_pass','Wrong Username and password'); // for wrong password
redirect('admin/login');
}
}
}
How do I store an array() of data from a form into a session in Codeigniter?
I want to store the email data so I can use it to retrieve the first name from the database with the help of the model .
Below is my code, which I can't get working:
public function index()
{
if (isset($this->session->userdata['logged_in'])) {
redirect('admin_panel');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');
if ($this->form_validation->run() !== false) {
$this->load->model('admin_model');
// then validation passed . Get data from the base
$res = $this->admin_model->verify_user($this->input->post('email_address'), $this->input->post('password'));
if ($res !== false) {
// person has an account
$session_data = array(
'id' => $row[0]->id,
'email' => $row[0]->email_address,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
redirect('admin_panel');
}
Would be nice to know a proper way of doing this . I am pretty new to Codeigniter, and only recently became familiar with MVC.
i am sorry for not giving enough detail. i posted only part of the code. I was only interested in how i would store a login form data into a session and how to retrieve it.
Below is the full code of the controller - nxlogin.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Nxlogin extends CI_Controller {
function __contruct()
{
parent::__contruct();
session_start();
}
public function index()
{
if (isset($this->session->userdata['logged_in'])) {
redirect('admin_panel');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('email_address', 'Email Address', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');
if ($this->form_validation->run() !== false) {
$this->load->model('admin_model');
// then validation passed . Get data from the base
$res = $this->admin_model->verify_user($this->input->post('email_address'), $this->input->post('password'));
if ($res !== false) {
// person has an account
$session_data = array(
'id' => $row[0]->id,
'email' => $row[0]->email_address,
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
redirect('admin_panel');
}
}
$this->load->view('login_view');
}
public function logout()
{
$sess_array = array(
'id' => '',
'email' => ''
);
$this->session->unset_userdata('logged_in', $sess_array);
redirect('nxlogin');
}
}
This is my model - admin_model.php
<?php
class Admin_model extends CI_Model {
function __construct()
{
}
public function verify_user($email, $password)
{
$q = $this->db->where('email_address', $email)->where('password', sha1($password))->limit(1)->get('adminusers');
if ($q->num_rows > 0) {
return $q->row();
}
return false;
}
public function get_data($id)
{
$q = $this->db->get_where('adminusers', array('id' => $id));
if ($q->num_rows > 0) {
return $q->result();
}
return false;
}
}
Now what I want to do is to store the email into the session array , and then later use it to retrieve data - like full name - from the particular database row that has that email , in the admin_panel.php - controller ; which is the admin main page. the code is:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin_panel extends CI_Controller {
public function __construct()
{
session_start();
parent::__construct();
if (!isset($this->session->userdata['logged_in'])) {
redirect('nxlogin');
}
}
public function index()
{
$this->load->view('admin_panel');
}
public function profile()
{
if (isset($this->session->userdata['logged_in']))
{
$id = isset($this->session->userdata['logged_in']) ;
$this->load->model('admin_model');
$data['query'] = $this->admin_model->get_data($id);
$this->load->view('profile', $data);
}
}
}
I also saw that you used this code when storing information into the session array -
$session_data = array(
'id' => $row[0]->id,
'email' => $row[0]->email_address,
);
why is it $row[0] for both?
spotted a few issues.
first. in your model verify_user() method you are returning row()
CI docs here shows that row() returns an object with the first single results.
second. in your Nxlogin controller index() method, your row() is being loaded into $res, but then you reference row[0] which is incorrect. reference your results like
$res->id and $res->email_address
third. you should initialize your session with
$this->load->library('session'); in your controller constructor and place it AFTER parent::__construct(); as documented here where you have mixed this up in Admin_panel controller. or use the auto-loaded
fourth. you have loaded the array against a key in your session. two options, (1) you should call get_data with $id['id'] in your Admin_panel profile method. or (2) load your array without the key. Nxlogin index() change $this->session->set_userdata('logged_in', $session_data); to $this->session->set_userdata($session_data); now reference your data with $this->session->userdata['id'] and $this->session->userdata['email'] which think what you're after.
last. also consider following codeigniters style guide here as your false should be uppercase for clarity.
good luck!
Hi i am not sure why are my codes not working.
This is the Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends CI_Controller {
public function __construct(){
parent::__construct();
if (! $this->session->userdata('is_logged_in')){
redirect('main/restricted');
} else {
$privilege = $this->session->userdata('privilege');
if ($privilege == 'member'){
redirect('main/restricted');
}
}
}
public function index() {
$this->load->model("model_books");
$data2 = $this->model_books->select_book();
$data = array(
'title' => 'Admin Page'
);
$this->load->view("header", $data);
$this->load->view("admin", $data2);
$this->load->view("footer");
}
This is the Model:
<?php
class Model_books extends CI_Model {
public function select_book(){
$query = $this->db->get('books');
if ($query){
return $query->result();
} else {
return false;
}
}
}
This is the View:
<?php
echo $data2->content;
?>
I got around 10 books inside the database however the books in the database are not showing up.
Try this
public function index() {
$this->load->model("model_books");
$data = array(
'title' => 'Admin Page',
'books' => $this->model_books->select_book()
);
$this->load->view("header", $data);
$this->load->view("admin", $data);
$this->load->view("footer");
}
In view
<?php
print_r($books);
?>
try the following in constructor function in model
$db = $this->load->database('default', TRUE);
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 {}