Codeigniter session ends after i close browser how to make remember checkbox ?
checkbox already in login form but i don't know how to do it ?
here's the login method in controller
public function login($page = 'login') {
if (!file_exists(APPPATH. '/views/main/' .$page. '.php')) {
// Whoops, we don't have a page for that!
show_404();
}
if($this->session->userdata('is_logged_in')) {
redirect('home');
$this ->session ->set_flashdata('alreadysignedin', '<div class="alert alert-info"><strong>Srroy !</strong> but you are already signed in.</div>');
} else {
$this ->load ->library('form_validation');
$data['title'] = ucfirst($page); // Capitalize the first letter
$this ->load ->model('users_model');
$this ->load ->view('include/header', $data);
$username = $this->input->post('username');
// Get User Role
$this->load->model('user_profile');
$this->user_profile->rolesdetail($username);
$userrole = $this->user_profile->rolesdetail($username);
// Get User Role </>
if ($this ->input ->post('login') AND $this->form_validation ->run('login') == TRUE) {
$data = array(
'id' => $userrole->id,
'username' => $this ->input ->post('username'),
'is_logged_in' => TRUE,
'roles' => $userrole->roles,
'email' => $userrole->email
);
$this ->session ->set_userdata($data);
$this ->session ->set_flashdata('logindone', '<div class="alert alert-success"><strong>Congratulation!</strong> you have logged in successfully.</div>');
redirect('home');
}
$this ->load ->view('main/'.$page, $data);
$this ->load ->view('include/footer', $data);
}
}
i read about cookies but i did not known how it works
It's simple, after submitting the form while verifying/processing the user credentials, if the checkbox value is found then create a cookie using $this->input->set_cookie(); after loading the cookie helper. Store the login info in that cookie and when the user arrives on login page check for that cookie and if data is present in that cookie just populate the form and its done. You can also keep the cookie data encrypted. check this link for further codeigniter cookies
Related
I get odd bugs in the process of logging using myth-auth. So I have a one page user that can be accessed without logging, and an admin page that requires the user to login if they want to access it. But after logging to the admin page, it redirect to the previous page. So I logged in again, and it can go into the admin page. The weird thing is, when I logged out, the same thing starts all over again.
I start to think there might be something wrong with the App/Config/Route page or the AuthController.
public function login()
{
// No need to show a login form if the user
// is already logged in.
if ($this->auth->check()) {
$redirectURL = session('redirect_url') ?? base_url('admin');
unset($_SESSION['redirect_url']);
return redirect()->to($redirectURL);
}
// Set a return URL if none is specified
$_SESSION['redirect_url'] = session('redirect_url') ?? previous_url() ?? base_url('admin');
return view($this->config->views['login'], ['config' => $this->config]);
}
/**
* Attempts to verify the user's credentials
* through a POST request.
*/
public function attemptLogin()
{
$rules = [
'login' => 'required',
'password' => 'required',
];
if ($this->config->validFields == ['email']) {
$rules['login'] .= '|valid_email';
}
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$login = $this->request->getPost('login');
$password = $this->request->getPost('password');
$remember = (bool)$this->request->getPost('remember');
// Determine credential type
$type = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
// Try to log them in...
if (!$this->auth->attempt([$type => $login, 'password' => $password], $remember)) {
return redirect()->back()->withInput()->with('error', $this->auth->error() ?? lang('Auth.badAttempt'));
}
// Is the user being forced to reset their password?
if ($this->auth->user()->force_pass_reset === true) {
// return redirect()->to(route_to('reset-password') .'?token='. $this->auth->user()->reset_hash)->withCookies();
return redirect()->to(route_to('reset-password') . '?token=' . $this->auth->user()->reset_hash);
}
$redirectURL = session('redirect_url') ?? base_url('admin');
unset($_SESSION['redirect_url']);
// return redirect()->to($redirectURL)->withCookies()->with('message', lang('Auth.loginSuccess'));
return redirect()->to($redirectURL)->with('message', lang('Auth.loginSuccess'));
}
and here the route page
// ROUTE USER
$routes->get('/', 'Page::index');
/* ROUTE PER-PAGE */
$routes->get('/admin', 'Page::admin');
I found the bugs, in the user views I write this code
<p>Login halaman Admin Login</p>
but if I access the admin page with url, it redirect to index.php/login. So i change <a href="/login"> to <a href"index.php/login">. So this is just url issues
I have an issue regarding session (userdata/flashdata) on my code.
Modal
public function loginCheck(){
$email = $this->input->post('email');
//encrypt password
$this->load->library("hashing");
$password = $this->hashing->incrypt($this->input->post('password'));
$this->params = array('email' => $email, 'password' => $password);
$user = $this->findById();
if(count($user)>0){
$data = array(
'email' => $user->email,
'isLoggedIn' => 1,
'user_id' => $user->id,
'user_type' => $user->user_type
);
$this->session->set_userdata($data);
return true;
}
return false;
}
And my Controller
public function login(){
$this->load->model('model_users');
//if posted login
$submit = $this->input->post('submit');
if($submit){
$this->load->model('model_users');
$rules = $this->model_users->rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == true){
// user credential from model
if($this->model_users->loginCheck()== true){
redirect("admin/site/index");
} else{
$this->session->set_flashdata('message', 'Oops! Invalid email and/ or password.');
redirect("admin/site/login");
}
}else{
$this->session->set_flashdata('message', 'Oops! Invalid email and/ or password.');
redirect("admin/site/login");
}
}
$this->loadPartialView("admin/login");
}
The session is not being set on CI 3.0. The function set_userdata() is not functioning well.
The manual session initializing is also having trouble.
Please try load Session Library into Controller and Modal before using it.
$this->load->library('session');
i dont think if this is a good answer, but have you call your session in view?
as i know ,
CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.
it can be found in sesseion documentation
so in your view in div tag or other, its like
<?php echo $this->session->flashdata('message');?>
First you can add library of session.
There are two way of add library.
1) You can add in controller method.
2) autoload in autoload.php file.
I am new in Codeigniter, I creat an login form and now i want to pass some session variables to my view and my model but i failed
here is my controller code where i start session
function validate_credentials(){
$this->load->model('users_model');
$query = $this->users_model->validate();
if($query){
$data = array(
'username'=> $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/dashboard');
}
else{
//echo "Wrong";
$this->index();
}
}
Here is my Model Code
<?php
class Site extends CI_Controller{
function _construct(){
parrent::Controller();
$this->is_logged_in();
}
function dashboard(){
$this->load->view('dashboard');
}
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. <a href="../login>Login</a>"';
die();
}
}
}
?>
And Here Is my View Code where actually i want session variable
<body>
<?php $session_id = $this->session->userdata('username');
echo $session_id;
?>
Members Area Olny...!!
</body>
</html>
Your Code is correct.
Make sure that you have loaded the Session library in the autoload.php file in configuration folder.
Codeigniter Porject folder
Application
Config
autoload.php
Open the autoload.php file and add session library
or
Copy and paste this code $this->load->library(‘session’); in the constructor.
I am not getting your question properly but I think that you want to use the session data in the model.
ok for that you can use this code.
// To Set a Data in Session
$session_data = array(
'username' => $this->input->post('username'),
'is_logged_in' => TRUE
);
$this->session->set_userdata('user_data', $session_data);
// To get the session data
$session_data = $this->session->userdata('user_data');
$user_name = $session_data['username'];
$login_status = $session_data['is_logged_in'];
//Now you can use this data in the model.
I hope I make it clear for you.
One other question – in the user controller login method, after checking pressed button (login or forget password), in line : $data = $this->user_model->login(); return correct user information; "user name, family, user id" to be used in dashboard for using in log table and heAder of pages how to send this data to dashboard?
i tried to send it via redirect() but it fail
if ($this->form_validation->run() == TRUE) {
if (!empty($_POST['login'])) {
$data = $this->user_model->login();
if ($data != NULL)
{
redirect('dashboard');
} else {
redirect('user/login', 'refresh');
}
} elseif (!empty($_POST['forget'])) {
redirect('user/recover');
}
}
$this->data['subview'] = 'users/login';
$this->load->view('users/_layout_modal', $this->data);
Function redirect() doesn't save anything. You can try save $data to session by writing $this->session->set_userdata('some_name', $data);
Then you can call them with $this->session->userdata('some_name');
Note that $data can be object or array.
Assume that $data is array, then in dashboard you can use something like this:
$data = $this->session->userdata('some_name');
echo 'Username: '.$data['username'].'<br />';
echo 'Family: '.$data['family'];
...... so on ........
As per your question, you are validating the user login details and creating session for them.
Then store user information in session.
set session library auto-load in config/autoload.php. Then create session as below.
$this->session->set_userdata(
array(
"username"=>$username,
"user_id" => $user_id,
"family" => $family
)
);
In Dashboard:
You can access session with it's name:
echo $this->session->userdata("username");
I am at the tail end of signing in a created user to an account. I've commented out my flow and everything seems to make since, however I am missing a step or two because now the post data password is not being hashed.
CONTROLLER:
function validate_credentials()
{
// WHEN THE VIEW IS LOADED THIS FUNCTION IS CALLED AND LOADS MODEL AS WELL AS DEFINES THE SALT VARIABLE AND LOADS THE ENCRYPTING HELPER LIBRARY
$this->load->model('user_model', 'um');
$login = $this->input->post('submit');
$salt = $this->_salt();
$this->load->library('encrypt');
//IF THE SUBMIT BUTTON IS TRIGGERED THE POST DATA IS SENT TO THE VALIDATE FUNCTION IN THE MODEL VIA VARIABLES CREATED
if($login)
{
$data = array(
'email' => $this->input->post('email'),
'password' => $this->encrypt->sha1($user->salt. $this->encrypt->sha1($this->input->post('password')))
);
$user = $this->um->validate($data);
}
// IF ITS A REAL USER OPEN THE GATE AND LET THEM IN
if($user)
{
$this->session->set_userdata($data);
redirect('account/dashboard');
}
else
{
$this->index();
}
}
MODEL:
function validate($data)
{
$this->output->enable_profiler(TRUE);
// TAKING THE DATA FROM THE MODEL AND CHECKING IT AGAINST THE STORED INFO IN THE DB
$query = $this->db->where($data)->get('users', 1);
if($query->row())
{
return $query->row();
}
}
thanks in advance
$user->salt should just be $salt.