I Have Some Problems in codeigniter with sessions - php

I try to check when someone logged in his/her account show the page with the session, I loaded session in libraries but the session doesn't work
And Sorry For My Bad English
Thanks For The Help :)
This Is The Model
class login_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function check()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$remember = $this->input->post('remember');
$this->db->select('username','password');
$this->db->from('user');
$this->db->where('username',$username);
$this->db->where('password',md5($password));
$result = $this->db->count_all_results();
if($result > 0)
{
$data_session = array(
'username'=>$username,
'islogin'=>true,
);
$this->session->set_userdata($data_session);
redirect('post/index');
}
This Is The Controller
class Post extends CI_Controller
{
public function index()
{
$login = $this->session->userdata('islogin');
if($login == true)
{
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}
else {
redirect('login/index');
}
}
}
This Is The Config
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'weblogdata';
$config['sess_expiration'] = 3600;
$config['sess_save_path'] = 'tbl_ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;
$config['encryption_key'] = m.D~wt,wA:MjS9$]g<H4Z7eW.7`0vDbX$F`LUgCg+>$1?0L$vq1:7vaVf&d{U(

set your session condition on contruct(), change the controller to be like this :
function __construct() {
parent::__construct();
if($this->session->userdata('islogin') != true)
{
redirect('login/index');
}
}
function index() {
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}

change your code to this
class Post extends CI_Controller
{
public function index()
{
$login = $this->session->userdata('islogin'); // $login will be 1
if($login)
{
$data = array (
'name' => 'Hello',
);
$this->load->view('post/index',$data);
}
else {
redirect('login/index');
}
}
}

Related

Login Attempts - Codeigniter - Not Working

I want to workout a function such that unsuccessful login attempts of user are capped at 3 consecutive failed login attempts, then serve them a message to that effect. It is immediately executing this line:
if ($isBlocked) {
$this->form_validation->set_message('check_user', 'Account is temporarily blocked.');
}
Somethings wrong on my code. Thanks in advance for the help.
Controller
<?php
class Account_login extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['title'] = 'Account Login';
$this->load->view('account_login', $data);
}
public function verify()
{
$this->form_validation->set_rules('acc_username', 'Username', 'required');
$this->form_validation->set_rules('acc_password', 'Password', 'required|callback_check_user');
if ($this->form_validation->run() === TRUE) {
echo 'Success';
} else {
$this->index();
}
}
public function check_user()
{
$username = $this->input->post('acc_username');
$password = $this->input->post('acc_password');
$this->load->model('account_login_model');
$login = $this->account_login_model->login($username, $password);
if ($login) {
return true;
} else {
if (isset($_SESSION['error_count'][$username])) {
$_SESSION['error_count'][$username] += 1;
} else {
$_SESSION['error_count'][$username] = 1;
}
$isBlocked = $this->account_login_model->isBlocked($username);
if ($isBlocked) {
$this->form_validation->set_message('check_user', 'Account is temporarily blocked.');
} else if (isset($_SESSION['error_count'][$username]) && $_SESSION['error_count'][$username] > 2) {
$this->account_login_model->block($username);
$this->form_validation->set_message('check_user', '3 consecutive failed login attempts. Account Blocked.');
} else {
$this->form_validation->set_message('check_user', 'Invalid Username/Password');
}
return false;
}
}
}
Model
<?php
class account_login_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function login($username, $password)
{
$condition_array = array(
'acc_username' => $username,
'acc_password' => $password
);
$rs = $this->db->get_where('accounts', $condition_array);
return $rs->row_array() ?: false;
}
public function isBlocked($username)
{
$condition_array = array(
'acc_username' => $username,
'acc_isBlocked' => 1
);
$rs = $this->db->get_where('accounts', $condition_array);
$row_count = count($condition_array);
if ($row_count > 0) {
return true;
} else {
return FALSE;
}
}
public function block($username)
{
$this->load->library('email');
$email = $this->account_lookup($username, 'acc_email');
$this->email->from('<email>', 'Yahoo.com');
$this->email->to($email);
$this->email->subject('Account Blocked');
$message = $this->load->view('account_blocked', null, TRUE);
$this->email->message($message);
$this->email->send();
$this->db->where('acc_username', $username);
return $this->db->update('accounts', array('acc_isBlocked' => 1));
}
public function account_lookup($username, $return)
{
$rs = $this->db->get_where('account', array('acc_username' => $username));
$row = $rs->row();
return $row->$return;
}
}

how to display home page after successfull login with codeigniter?

I tried redirect() and $this->load->view('target_page') but, no success for me so please help me with this:
My controller is here:
class Login_control extends CI_Controller {
public function index() {
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername'])|| isset($_POST['Logpassword']))
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data > 0 )
{
echo '<font color="#00FF00">'. "OK".'</font>';
$this->load->view('testing',$data);
}
else
{ echo '<font color="#FF0000">'. "Login Failed ! Username or Password is Incorrect.".'</font>' ;
}
exit();
}
$this->load->view('signup_view');
}
}
Try this code. You have written echo before redirect so, it might not work.
class Login_control extends CI_Controller{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername'])|| isset($_POST['Logpassword']))
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data > 0 )
{
redirect('testing');
}
else
{ echo '<font color="#FF0000">'. "Login Failed ! Username or Password is Incorrect.".'</font>' ;
}
exit();
}
$this->load->view('signup_view');
}
}
Try this
In Controller
class Login_control extends CI_Controller{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
if(isset($_POST['Logusername']) && isset($_POST['Logpassword'])) # Change || to &&
{
$user = $_POST['Logusername'];
$pass = $_POST['Logpassword'];
$data = $this->login_model->login1($user,$pass);
if($data == 1){ # check is there only one user
echo '<font color="#00FF00">OK</font>';
$this->load->view('testing',$data);
}
else{
echo '<font color="#FF0000">Login Failed ! Username or Password is Incorrect.</font>' ;
}
}
$this->load->view('signup_view');
}
}
In Model
public function login1($user,$pass)
{
$query = $this->db->query("SELECT * FROM user WHERE username= '$user' AND password = '$pass' ");
$result = $query->result_array();
$count = count($result); # get count of result
return $count; # return count to controller
}
As you are developing in codeigniter better user its inbuilt method to get and post data. For authentication u can create one library which will be autoload and check for session like userid if not found then redirect user to login page . You can create one array in that library which will defines the public / authenticated pages on bases on which you prevent user from accessing authenticated pages. You can try this for Controller :
class Login_control extends CI_Controller
{
public function index()
{
$this->load->model('login_model');
$this->load->helper('url');
$Logusername = $this->input->post('Logusername', true);
$Logpassword = $this->input->post('Logpassword', true);
if (!empty($Logusername) && !empty($Logpassword)) {
$user = $Logusername;
$pass = $Logpassword;
$data = $this->login_model->authenticate($user, $pass);
if ($data == TRUE) {
/* User this flashdata to display the message after redirect */
$this->session->set_flashdata('success', 'Logged in successfully');
redirect(site_url("dashboard"));
} else {
/* User this flashdata to display the message after redirect */
$this->session->set_flashdata('success', 'Wrong Username/password');
redirect(site_url());
}
}
$this->load->view('signup_view');
}
}
For Model
public function authenticate($Logusername, $Logpassword)
{
$select_col = "iUserId";
$where = "`vUserName` =?"; //*
$where.=" AND BINARY `vPassword`=?";
$sql = "SELECT " . $select_col . " FROM user WHERE " . $where . "";
$result = $this->db->query($sql, array($Logusername, $Logpassword))->result_array();
if (is_array($result) && count($result) > 0) {
/* Create Session and store userid */
$this->session->set_userdata("iUserId", $result[0]["iUserId"]);
return TRUE;
} else {
return FALSE;
}
}
There are many ways to authenticate the user. Check for hooks in Codeigniter

How can I pass variable between controller functions

This is my first time doing web programming. I want to make one variable that I can use on some functions, I use public $username; and public $password; and use $this->username and $this->password; but it didn't work. This is my code on controller;
public $can_log ;
public function home(){
$this->load->model("model_get");
$data["results"] = $can_log;
$this->load->view("content_home",$data);
}
public function login(){
$this->load->view("site_header");
$this->load->view("content_login");
$this->load->view("site_footer");
}
public function login_validation(){
$this->load->library('form_validation');
$this->load->view("site_header");
$this->load->view("site_nav");
$this->form_validation->set_rules('username','Username','required|trim|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|trim');// use md5 if want to encrpyt this
if($this->form_validation->run()){
redirect('site/home');
} else {
$this->load->view('content_login');
}
}
public function validate_credentials(){
$this->load->model('model_get');
$username = $this->input->post('username');//"user";
$password = $this->input->post('password');//"password";
//I tried both but none of those work
$this->can_log = $this->model_get->can_log_in($username, $password);
if($this->can_log){
return true;
} else {
$this->form_validation->set_message('validate_credentials','Incorrect username/password.');
return false;
}
}
I also tried with public $username and public $password but still can't get it
on my model;
public function can_log_in($username, $password){
$query = $this->db->query("SELECT col1, col2 FROM table1 where id_login = '$username' and id_password = '$password'");
if($query->num_rows() > 0) {
$data = $query->result(); // fetches single row: $query->row();
return $data; //fetches single column: $data->col1;
}
}
so how can I get can_log - that contains col1 and col2 - to other function?
Maybe something like this?
public function with_parameter($parameter)
{
do something with $parameter
}
And then call the function
with_parameter($can_log);
I didn't understood the exact requirements, but try below code if it works for you.
Have followed some CI guidelines which you need to learn.
Controller:
class Controller_name extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model("model_get"); // load models in constructor
$this->can_log = "some value"; // is the way to define a variable
}
public function home()
{
$data["results"] = $this->can_log; // is the way to retrieve value
$this->load->view("content_home",$data);
}
public function validate_credentials()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$is_valid = $this->model_get->can_log_in($username, $password);
if($is_valid)
{
return true;
}
else
{
$this->form_validation->set_message('validate_credentials','Incorrect username/password.');
return false;
}
}
}
Model:
class Model_get extends CI_Model
{
public function can_log_in($username, $password)
{
$where_aray = array("id_login" => $username, "id_password" => $password);
$query = $this->db->get_where("table", $where_array);
if($query->num_rows() > 0)
return $query->row();
return false;
}
}

Function won't pass variable to view

Right now $renderData['username'] won't pass through to the view.
class HomeController extends MY_Controller {
public function index($renderData=""){
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$renderData['username'] = $session_data['username'];
//$this->load->view('pages/home_view', $renderData);
$this->_render('pages/home',$renderData);
}
else
{
//If no session, redirect to login page
redirect('LoginController', 'refresh');
}
}
}
The error I get is...
Which alludes to this code...
<h1>Home</h1>
<h2>Welcome <?php echo $username; ?>!</h2>
Logout
Here is my My_Controller where the _render function is located...
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller{
//Page info
protected $data = Array();
protected $pageName = FALSE;
protected $template = "main";
protected $hasNav = TRUE;
//Page contents
protected $javascript = array();
protected $css = array();
protected $fonts = array();
//Page Meta
protected $title = FALSE;
protected $description = FALSE;
protected $keywords = FALSE;
protected $author = FALSE;
function __construct()
{
parent::__construct();
$this->data["uri_segment_1"] = $this->uri->segment(1);
$this->data["uri_segment_2"] = $this->uri->segment(2);
$this->title = $this->config->item('site_title');
$this->description = $this->config->item('site_description');
$this->keywords = $this->config->item('site_keywords');
$this->author = $this->config->item('site_author');
$this->pageName = strToLower(get_class($this));
}
protected function _render($view,$renderData="FULLPAGE") {
switch ($renderData) {
case "AJAX" :
$this->load->view($view,$this->data);
break;
case "JSON" :
echo json_encode($this->data);
break;
case "FULLPAGE" :
default :
//static
$toTpl["javascript"] = $this->javascript;
$toTpl["css"] = $this->css;
$toTpl["fonts"] = $this->fonts;
//meta
$toTpl["title"] = $this->title;
$toTpl["description"] = $this->description;
$toTpl["keywords"] = $this->keywords;
$toTpl["author"] = $this->author;
//data
$toBody["content_body"] = $this->load->view($view,array_merge($this->data,$toTpl),true);
//nav menu
if($this->hasNav){
$this->load->helper("nav");
$toMenu["pageName"] = $this->pageName;
$toHeader["nav"] = $this->load->view("template/nav",$toMenu,true);
}
$toHeader["basejs"] = $this->load->view("template/basejs",$this->data,true);
$toBody["header"] = $this->load->view("template/header",$toHeader,true);
$toBody["footer"] = $this->load->view("template/footer",'',true);
$toTpl["body"] = $this->load->view("template/".$this->template,$toBody,true);
//render view
$this->load->view("template/skeleton",$toTpl);
break;
}
}
}
Here is an additional function that may be helpful...
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('pages/login_view');
}
else
{
//Go to private area
// redirect('home', 'refresh');
redirect('HomeController', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
What am I doing wrong that is preventing the username to be passed to the view?
PS - let me know any additional documentation I can provide.
something like this
protected function _render($view,data, $renderData="FULLPAGE") {
$this->data = $data;
switch ($renderData) {
case "AJAX" :
$this->load->view($view,$this->data);
break;
case "JSON"

Codeigniter - logout link doesn't works - session and cookies not destroyed

i made a simple logout url with the controller and it looks like this:
class Auth extends MX_Controller{
function logout(){
$this->session->sess_destroy();
$this->bootstrap->unsetUserCookie();
redirect(base_url(),'',301);
}
}
then
class Bootstrap{
function unsetUserCookie(){
$CI =& get_instance();
$CI->input->set_cookie(
array(
'name'=>'remember_me',
'value'=>'',
'expire'=>''
));
$CI->input->set_cookie(
array(
'name'=>'remember_me_n',
'value'=>'',
'expire'=>''
));
$CI->input->set_cookie(
array(
'name'=>'duser_lang',
'value'=>'',
'expire'=>''
));
$CI->input->set_cookie(
array(
'name'=>'duser_country',
'value'=>'',
'expire'=>''
));
}
}
i'm using the session DB these are the config params i'm using:
$config['sess_cookie_name'] = 'sess_id';
$config['sess_expiration'] = 0; //24hours -> 8640
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_session';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 3000000000;
then i created a simple session library and don't know if this can block anything but i guess no cause i receive no errors at all:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*We encode/decode all session data in base64 to avoid problems with multybityes data*/
class MY_Session extends CI_Session {
function set_userdata($data, $singleVar = NULL) {
if(is_array($data)){
$newValues = array();
foreach ($data as $key=>$value) {
$newValues[$key] = base64_encode($value);
}
parent::set_userdata($newValues);
}
else{
if(is_array($singleVar)){
$newValues = array();
foreach ($singleVar as $key=>$value) {
$newValues[$key] = base64_encode($value);
}
//Encode $singleVar
parent::set_userdata($data, $newValues);
}else{
parent::set_userdata($data, base64_encode($singleVar));
}
}
}
function set_flashdata($data, $singleVar = NULL) {
if(is_array($data)){
$newValues = array();
foreach ($data as $key=>$value) {
$newValues[$key] = base64_encode($value);
}
parent::set_flashdata($newValues);
}
else{
if(is_array($singleVar)){
$newValues = array();
foreach ($singleVar as $key=>$value) {
$newValues[$key] = base64_encode($value);
}
//Encode $singleVar
parent::set_flashdata($data, $newValues);
}else{
parent::set_flashdata($data, base64_encode($singleVar));
}
}
}
public function userdata($item) {
$data = parent::userdata($item);
if(is_array($data)){
$newData = array();
foreach ($data as $key => $value) {
$newData[$key] = base64_decode($value);
}
return $newData;
}else{
//Decode $data
return base64_decode($data);
}
}
}
/* End of file */
/* Location: ./application/controllers/ */
?>
the url is so simple,it just had to delete session and cookies, but the session and the cookies seems not to be deleted cause after launching the logout url i'm still logged.
Any clue please?
you code is fasle :
class Auth extends MX_Controller{
function logout(){
$this->session->sess_destroy();
$this->bootstrap->unsetUserCookie();
redirect(base_url(),'',301);
}
}
this extends is MY_Controller,
class Auth extends MY_Controller{
I had the same issue, it was the cache problem. It could be solved by adding the below header code inside the constuctor function or any other function where the login code is related.
header("Cache-Control: no-cache, must-revalidate");

Categories