I'm trying to make a login system using codeigniter but there is a fatal error found when trying to login :(
Controler Auth.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
function __construct(){
parent::__construct();
$this->load->model('Auth/login','',TRUE);
}
class Auth extends CI_Controller {
public function index()
{
// $this->load->view('Home');
}
// start login
public function login()
{
$this->load->helper(array('form'));
$this->load->view('Login');
}
// end login
// start logout
public function logout()
{
$this->session->unset_userdata('logged_in');
redirect('Login','refresh');
}
// end logout
// start checkLogin
public function checkLogin()
{
// field validation successfull, validate against database
$username = $this->input->post('username');
$password = $this->input->post('password');
// query database
$this->load->model('Auth');
$result = $this->Auth->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('checkLogin', 'Invalid username or password');
return FALSE;
}
}
// end checkLogin
}
Models Auth.php
<?php
class Auth extends CI_Model
{
// start login
function login($username, $password)
{
$this->db->select('id','username','password');
$this->db->from('user_details');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
}else{
return false;
}
}
// end login
}
?>
please help me to find the exact error I have done :'(
The problem is you have two class with same name Auth one for controller and one for model.One script cannot contain two class that's why you got that error.
Rename your auth model like this Auth_model.php and declare class like this
class Auth_model extends CI_Model
Hope you can do rest how to use this model.
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.
I've created a PHP desktop application, but after login, I want to redirect to the controller, but I'm getting error:
redirect('dashboard');
Loading error (-102).
and when I like something this:
redirect('https://www.google.com/');
it works.
How can I redirect to a controller?
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('LoginModel','LoginModel');
}
public function index()
{
if(!empty($_POST))
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$result = $this->LoginModel->login($email,$password);
if($result -> num_rows() > 0)
{
foreach ($result->result() as $row)
{
$this->session->userid = $row->id;
$this->session->email= $row->email;
$this->session->is_admin = $row->is_admin;
**redirect('dashboard');**
}
}
else
{
$data['email'] = $email;
$data['password'] = $password;
$this->session->set_flashdata('SUCCESSMSG','Email and Password is Wrong');
$this->load->view('login',$data);
}
}
else
{
$this->load->view('login');
}
}
public function logout()
{
$this->session->sess_destroy();
redirect('login');
}
}
I think you need to use redirect to relative path; try something like this:
redirect('/controller_name/Dashboard');
I have successfully created a registration and login system.
I have used username and password in the login form and i want to put the userid in other form like hidden field
login model cliente.php:
public function login($username,$password){
$this->db->select('IdCliente');
$this->db->where('LoginCliente',$username);
$this->db->where('PassCliente',$password);
$q = $this->db->get('clientes');
if($q->num_rows()>0){
return true;
}else{
return false;
}
login controller login.php:
public function index(){
if($this->session->userdata('LoginCliente')){
redirect('profile');
}
if(isset($_POST['password'])){
$this->load->model('cliente');
if($this->cliente->loginemp($_POST['username'],$_POST['password'])){
$this->session->set_userdata('Login',$_POST['username']);
redirect('PanelIndex');
}elseif(isset($_POST['password'])){
$this->load->model('cliente');
if($this->cliente->login($_POST['username'],$_POST['password'])){
$this->session->set_userdata('LoginCliente',$_POST['username']);
$this->session->userdata('IdCliente');
redirect('profile');
}else{
redirect('login');
}
}
}
$this->load->view('inicio/loginview');
}
profile.php
public function index()
{
$this->load->view("/clientes/clienteindex");
}
If you want to IdCliente you need to return it first from the login function.
public function login($username,$password){
$this->db->select('IdCliente,LoginCliente');
$this->db->where('LoginCliente',$username);
$this->db->where('PassCliente',$password);
$q = $this->db->get('clientes');
if($q->num_rows()>0){
return $q->row_array();
}else{
return false;
}
}
Now In Index Function:
$session_data = $this->cliente->login($_POST['username'],$_POST['password'])
if(isset($session_data) && !empty($session_data){
$this->session->userdata('session_data',$session_data);
redirect('profile');
}
At the Profile(at the View):
$session_data = $this->session->userdata('session_data');
$IdCliente= $session_data['IdCliente'];
$LoginCliente= $session_data['LoginCliente'];
Create Simple_login.php file from your CI libraries folder and put this code.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/******************
* SHAHBLOGGER.COM*
******************/
class Simple_login {
// SET SUPER GLOBAL
var $CI = NULL;
/**
* Class constructor
*
* #return void
*/
public function __construct() {
$this->CI =& get_instance();
}
public function login($email, $password, $referer) {
//check username and password
$query = $this->CI->db->get_where('clientes',array('LoginCliente'=>$username,'PassCliente' => $password)); // better use md5($password)
if($query->num_rows() == 1) {
//let start query
$row = $query;
$user = $row->row();
$id = $user->IdCliente;
//set session user
$this->CI->session->set_userdata('id', $id);
redirect($referer);
}else{
//redirect them to you login page
redirect(site_url('login'));
}
return false;
}
/* check If They're login. If yes, set userdata */
public function check_login() {
//check session id set or not set. if not set, they're not login
if($this->CI->session->userdata('id') == '') {
//they're not login so redirect them to login page
redirect(site_url('login'));
}
}
// Unset session data
public function logout() {
$this->CI->session->unset_userdata('id');
redirect(site_url('login'));
}
}
then modify your controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller { //<<-- change 'Login' to your own class base on your controller file name
public function index() {
// Fungsi Login
$valid = $this->form_validation;
$username= $this->input->post('username');
$password = $this->input->post('password');
$referer = $_SERVER['HTTP_REFERER'];// change where you want user redirect after success login
$valid->set_rules('username','Username','required');
$valid->set_rules('password','Password','required');
if($valid->run()) {
$this->simple_login->login($username,$password, $referer);
}
// End login
$this->load->view('you_login_view');
}
public function logout(){
$this->simple_login->logout();
}
}
makesure activated Codeigniter Autoload features. Follow this link
to call id of login user use this $this->session->userdata('id');
to make page only can access by login user user, paste this at controller $this->simple_login->check_login();
Updated: Base on comment below. I've changed Query to modified Query (Codeigniter Active Record) to avoid SQL Injection
This is my Login controller
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function index($msg = NULL)
{
$this->load->helper('url');
// Load the model
$this->load->model('login_model');
// Validate the user can login
$this->login_model->loginAction();
}
}
?>
And my Model Login_model is
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function loginAction()
{
// grab user input
$email = $this->input->get('email');
$password = $this->input->get('password');
// Prep the query
$this->db->where('email', $email);
$this->db->where('password', $password);
// Run the query
$query = $this->db->get('users');
foreach ($query->result() as $row)
{
$dbid= $row->id;
$dbemail= $row->email;
}
$value=$query->num_rows();
if($value == 1)
{
$details = array(
'status'=>'sucess',
'message'=>'sucessfully logedin ',
'id' => $dbid,
'email' => $dbemail,
);
echo json_encode($details);
}
else
{
$detail = array(
'status'=>'failed',
'message'=>'invalid email password ',
);
echo json_encode($detail);
return false;
}
}
}
?>
This is working, but I need to use $details & $detail arrays in my Login controller to encode json data. for that what all modifications that I need to put in both my model and controller. I am new to codeIgniter.
Make changes as below
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function index($msg = NULL)
{
$this->load->helper('url');
// Load the model
$this->load->model('login_model');
// Validate the user can login
$result = $this->login_model->loginAction();
if($result['status'])
{
$details = array(
'status'=>'sucess',
'message'=>'sucessfully logedin ',
'id' => $result['data']->id,
'email' => $result['data']->email,
);
}else{
$detail = array(
'status'=>'failed',
'message'=>'invalid email password '
);
}
echo json_encode($detail);
}
}
?>
And my Model Login_model is
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function loginAction()
{
// grab user input
$email = $this->input->get('email');
$password = $this->input->get('password');
// Prep the query
$this->db->where('email', $email);
$this->db->where('password', $password);
// Run the query
$query = $this->db->get('users');
$value=$query->num_rows();
if($value == 1)
{
return ['status'=>true, 'data'=>$query->row_object()];
}
else
{
return ['status'=>false];
}
}
}
?>
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.