I have implemented the login logic in an MVC application; I want to see if the user has filled the username and passowrd incorrectly and if so I want to show a notifictaion in the view; so I'm passing this information via $data['er']; but for some reason it is not catching this data:
Please let me know if my question is clear or not; and if any clarification is needed, please let me know which part is ambiguous
My code:
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$GLOBALS['er'] = False;
}
public function index() {
$data['er']=$GLOBALS['er'];
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
public function validate_credentials() {
$this->load->model('user_model');
$query = $this->user_model->validate();
if ($query) {
$data = array(
'username' => $this->input->post('username'),
);
$this->session->set_userdata($data);
redirect('project/members_area');
} else {
$GLOBALS['er'] = TRUE;
$this->index();
}
}
}
Don't use GLOBALS you can just use a private variable in your class.
Create the variable above your __construct function like private $er
In your __contruct function set the default value
Set and get in your public function using $this->er
Implemented in your code:
class Login extends CI_Controller {
private $er;
public function __construct() {
parent::__construct();
$this->er = FALSE;
}
public function index() {
$data['er']= $this->er;
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
public function validate_credentials() {
$this->load->model('user_model');
$query = $this->user_model->validate();
if ($query) {
$data = array(
'username' => $this->input->post('username'),
);
$this->session->set_userdata($data);
redirect('pmpBulletin/members_area');
//die(here);
} else {
$this->er = TRUE;
$this->index();
}
}
}
Related
I have a $send variable in my model. I want to use it on the controller. But I get an error. How can I call it to the controller?
Model:
public function register_user($send)
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return true;
} else {
return false;
}
Controller:
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$this->users->register_user();
$this->load->view('signup', $this->send);
}
You can declare a private variable, say send in your model and make getter and setter in your model class in an encapsulated way to get the value in the controller, like below:
Snippet:
Model:
<?php
class Yourmodel extends CI_Model{
private $send;
function __construct() {
parent::__construct();
$this->send = [];
}
public function register_user($send){
if($this->emailVerify()) {
$this->send = array(
'tipo' => 'Error.'
);
return true;
}
return false;
}
public function setSendValue($value){
$this->send = $value;
}
public function getSendValue(){
return $this->send;
}
}
Controller:
<?php
class Controller extends CI_Controller{
private $send;
public function __construct(){
parent::__construct();
$this->send = [];
}
public function register(){
$this->load->model('users');
if($this->users->register_user()){
$this->send = $this->users->getSendValue();
}
$this->load->view('signup', $this->send);
}
}
Replace your code modal and controller as follows:
You need not to declare $send in modal definition, as you are not passing any value while calling the same modal function.
modal positive return can be array $send itself
Catch value of modal function
Modal :
public function register_user()
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return $send;
} else {
return false;
}
Controller:
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$send = $this->users->register_user();
//print_r($send); // You will get data here
$this->load->view('signup', $this->send);
}
Model
public function register_user($send = "")
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return $send;
} else {
return false;
}
Controller
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$sendRes = $this->users->register_user(); //now you can use this $send response variable
$this->load->view('signup', $this->send);
}
My code is as below
In login controller I've used
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
}
/**
* Check if the user is logged in, if he's not,
* send him to the login page
* #return void
*/
public function index() {
if ($this->session->userdata('is_logged_in')== TRUE) {
$refered_from = $this->session->userdata('refered_from');
redirect($refered_from,'refresh');
} else {
$this->load->view('login_page');
}
}
/**
* check the username and the password with the database
* #return void
*/
function validate_credentials() {
$this->load->model('Login_model');
$user_name = $this->input->post('uname');
$password = $this->input->post('password');
$is_valid = $this->Login_model->validate($user_name, $password);
if ($is_valid) {
$data = array(
'uname' => $user_name,
'is_logged_in' => TRUE
);
$this->session->set_userdata($data);
redirect('/Dashboard');
} else { // incorrect username or password
$data['message_error'] = TRUE;
$this->load->view('login_page', $data);
}
}
}
and I want access this session variable in dashboard
My Dashboard is
class Dashboard extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
}
public function index() {
if ($this->session->userdata('is_logged_in') == TRUE) {
$data['page_title'] = "Dashboard";
$data['main_content'] = 'Dashboard';
$this->load->view('includes/template', $data);
$this->session->set_userdata('refered_from', current_url());
} else {
redirect('/Login', 'refresh');
}
}
}
But it's not working
I've added session library in autoload.php file
Is there any change in config.php file?
I have Controller called login.php that will take login credentials, if true user will be directed to a method profile() in another controller called page.php.
In that profile() method only contain a command to load the view of user's profile.
So the route is like this:
Home->login->profie
But when I try to bypass the login process via url like this
Home->profile
The system still accept that. How can I make a rule that a user can't open profile if they're not logged in?
Here's the Controller:
page.php
class page extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('User_model', 'user_model', TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
function index() {
$this->load->view('page_header');
$this->load->view('content_front');
$this->load->view('page_footer');
}
function login() {
$this->load->view('page_header');
$this->load->view('content_login');
$this->load->view('page_footer');
}
function register() {
$this->load->view('page_header');
$this->load->view('content_register');
$this->load->view('page_footer');
}
function profile(){
$this->load->view('page_header');
$this->load->view('content_profile');
$this->load->view('page_footer');
}
function success() {
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
function logout()
{
//destroy session
$data = array('login' => '', 'uname' => '', 'uid' => '');
$this->session->unset_userdata($data);
$this->session->sess_destroy();
redirect('page/index');
}
}
?>
login.php
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html','security'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
//get form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//form validation
$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)
{
//validation fail
$this->load->view('content_login');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($username, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->username,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
$this->load->library('../controllers/page');
$this->page->profile();
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
$this->load->library('../controllers/page');
$this->page->login();
}
}
}
}
?>
Can anyone please help me how to fix this?
Thank you.
Add a constructor to every applicable controller.
Let the constructor check if the user is logged in, possibly by checking if a particular session exists. If it doesn't redirect to the login page.
Something like below
function __construct(){
parent::__construct();
if(!$this->session->userdata('userid')){
redirect('user/login');
}
}
use this at the top of the page you don't want it accessed when not logged in (supposing you've already set session data)
<?php if (!isset($_SESSION['username'])) {
redirect(base_url());
} ?>
Before showing that page, you should check whether that session exist or not, like if($this->session->userdata('username')). If exists, show that page, if not show any warning.
You can try
if ($this->session->userdata('login') == true) {
redirect('controller');
}
Login Controller
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html','security'));
$this->load->library(array('session','form_validation'));
$this->load->database();
$this->load->model('user_model');
}
function index()
{
if ($this->session->userdata('login') == true) {
redirect('controller');
}
//get form input
$username = $this->input->post('username');
$password = $this->input->post('password');
//form validation
$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)
{
//validation fail
$this->load->view('content_login');
}
else
{
//check user credentials
$uresult = $this->user_model->get_user($username, $password);
if(count($uresult)>0)
{
//set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->username,'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
$this->load->library('../controllers/page');
$this->page->profile();
}
else
{
$this->session->set_flashdata('msg','<div class = "alert alert-danger text-center">Wrong Email/Password</div>');
$this->load->library('../controllers/page');
$this->page->login();
}
}
}
}
Couple things I noticed also in Codeigniter 3 + versions the first letter must only be upper case on FILENAME and Controller Class
Also you don't need to close the controllers and model with ?> https://www.codeigniter.com/user_guide/general/styleguide.html#php-closing-tag
If for example you don't want the user to enter a function without login, you could check the session in the constructor of the class.
If it's only for a specific function, you could just also check the session in the function directly.
Create a helper file login_helper.php
function check_login( $session ) {
$CI =& get_instance();
$CI->load->helper('url');
if(!$session->userdata('login')){
redirect(base_url());
}
}
Now use this helper function in controllers where login is mandatory
class page extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('User_model', 'user_model', TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->status = $this->config->item('status');
$this->roles = $this->config->item('roles');
}
function index() {
$this->load->view('page_header');
$this->load->view('content_front');
$this->load->view('page_footer');
}
function login() {
$this->load->view('page_header');
$this->load->view('content_login');
$this->load->view('page_footer');
}
function register() {
$this->load->view('page_header');
$this->load->view('content_register');
$this->load->view('page_footer');
}
function profile(){
check_login();
$this->load->view('page_header');
$this->load->view('content_profile');
$this->load->view('page_footer');
}
function success() {
$this->load->view('page_header');
$this->load->view('content_success');
$this->load->view('page_footer');
}
function logout()
{
//destroy session
$data = array('login' => '', 'uname' => '', 'uid' => '');
$this->session->unset_userdata($data);
$this->session->sess_destroy();
redirect('page/index');
}
}
?>
Note: add login_helper in autoload.php in config folder.
$autoload['helper'] = array('login','url','cookie');
if($this->session->userdata('logged_in') == FALSE) {
$this->session->set_flashdata('error','<p class="alert alert-danger">Please login to view this page.</p>');
redirect('login_c');
exit;
}
My database:
this is my controller
class Account extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->model('m_login');
}
public function login() {
$this->load->view('login');
}
public function user() {
$data['login'] = $this->m_login->login();
redirect('home/index');
}
}
this is my model
<?php
class M_login extends CI_Model {
public function __construct() {
$this->load->database();
}
public function login() {
$username = $this->input->POST('username', TRUE);
$password = md5($this->input->POST('password', TRUE));
$data = $this->db->query("SELECT * from registrasi where username='$username' and password='$password' LIMIT 1 ");
return $data->row();
}
}
i create a new controller for redirect user to different function
public function index() {
switch ($this->session->userdata('level')) {
case 'dosen':
redirect('baprps/input_bap');
break;
case 'dosen koordinator':
redirect('baprps/grafik');
break;
case 'dekanat':
redirect('baprps/grafik');
break;
case 'mahasiswa':
redirect('baprps/verif_bap');
break;
default:
redirect('account/login');
break;
}
}
}
when i run it, no error but why function index always going to default and redirect to ('account/login'); ?? need some help thanks..
Please have a look in your code. You have close your class at here.
class M_login extends CI_Model {
public function __construct() {
$this->load->database();
}
public function login() {
$username = $this->input->POST('username', TRUE);
$password = md5($this->input->POST('password', TRUE));
$data = $this->db->query("SELECT * from registrasi where username='$username' and password='$password' LIMIT 1 ");
return $data->row();
}
}
But still you are trying to close after public function index() function, Please correct your code, then try again.
Hope this will help you.
Try this...I think you not need to make a new controller...
Controller:
<?php
class Account extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->model('m_login');
}
public function login() {
$this->load->view('login');
}
public function user() {
$this->m_login->login();
}
}
Model:
<?php
class M_login extends CI_Model {
public function __construct() {
$this->load->database();
}
public function login() {
$username = $this->input->POST('username', TRUE);
$password = md5($this->input->POST('password', TRUE));
$data = $this->db->query("SELECT * from registrasi where username='$username' and password='$password' LIMIT 1 ");
if ($data->num_rows() > 0)
{
$result = $data->row();
$this->load->library('session');
$this->session->set_userdata('level',$result->level);
$this->baprps();
}
else
{
redirect('home/index');
}
}
public function baprps() {
switch ($this->session->userdata('level')) {
case 'dosen':
redirect('baprps/input_bap');
break;
case 'dosen koordinator':
redirect('baprps/grafik');
break;
case 'dekanat':
redirect('baprps/grafik');
break;
case 'mahasiswa':
redirect('baprps/verif_bap');
break;
default:
redirect('account/login');
break;
}
}
}
OR
if you want to make a seperate controller
Change in controller to
public function user() {
$data['login'] = $this->m_login->login();
redirect('home/index');
}
TO
public function user() {
$data = $this->m_login->login();
$this->load->library('session');
$this->session->set_userdata('level',$data->level);
redirect('home/index');
}
The issue is that you forgot to set the session index 'level', so please edit the Account controller as follows:
class Account extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->model('m_login');
}
public function login() {
$this->load->view('login');
}
public function user() {
$data['login'] = $this->m_login->login();
$this->session->set_userdata('level',$data['login']['level']);
redirect('home/index');
}
}
I hope this may help you.
i am new in CodeIgniter (v.2.1.4). I have a problem with getting post from model.
I have a contoller:
class Login extends CI_Controller{
public function index(){
$data['main_view'] = 'login_form';
$this->load->view('login/include/template', $data);
}
public function validate(){
$this->load->library('form_validation');
$this->form_validation->set_rules('user', 'Име', 'trim|required|min_length[3]');
$this->form_validation->set_rules('pass', 'Парола', 'trim|required|min_length[4]');
if($this->form_validation->run()){
$this->load->model('users_model');
if($this->users_model->validate_login($username, $password)){
//valid user
}
else{
//not vlaid user
}
}
else{
$this->index();
}
}
}
and a model:
class Users_model extends CI_Model{
function __construct() {
parent::__construct();
}
function validate_login(){
$username = $this->input->post('user');
$password = md5($this->input->post('pass'));
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('users');
if($query->num_rows() == 1){
return TRUE;
}
else return FALSE;
}
}
When send via form (post) valid pair (username and password) nothing happens, but in apache2 log appears this:
PHP Fatal error: Call to a member function where() on a non-object in /var/www/ci/application/models/users_model.php
What is wrong?
Add a constructor to the Login class
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
}
}
Do you have database loaded? You need to load the database first.
You can either add it to /config/autoload.php to autoload database function:
$autoload['libraries'] = array('database');
Or call on demand like this:
$this->load->database();
More details here
Do Not Use post in model instead use this in controller like this
controller login.php
public function validate(){
$this->load->library('form_validation');
$this->form_validation->set_rules('user', 'Име', 'trim|required|min_length[3]');
$this->form_validation->set_rules('pass', 'Парола', 'trim|required|min_length[4]');
if($this->form_validation->run()){
$this->load->model('users_model');
$post = $this->input->post();
$data['username'] = $post['username'];
$data['password'] = md5($post['password']);
if($this->users_model->validate_login($data)){
//valid user
}else{
//not vlaid user
}
}
else{
$this->index();
}
}
Model
function validate_login($where){
$this->db->where($where);
$query = $this->db->get('users');
if($query->num_rows() == 1){
return TRUE;
}
return FALSE;
}
This should work. Remember calling post somehow doesn't work in model. I dont exactly know they reason.