How to redirect on controller? - php

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');

Related

Codeigniter can't login into home admin

Here is the controller, when I click the login button, nothing happens. What I want is to load the success screen when user data is validated and show error messages when user data is not validated.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct(){
parent::__construct();
}
public function index() {
$this->load->view('login');
}
function getlogin() {
$user = $this->input->post('username');
$pass = $this->input->post('password');
$user = $this->auth->log_admin($user,$pass);
if($user==true){
$this->session->set_userdata($user);
$data['hasil']=1;
echo json_encode($data);
}else{
$data['hasil'] = 0;
echo json_encode($data);
}
}
function logout(){
//helper_log("logout", "Logout");
$this->session->sess_destroy();
redirect('Login','refresh');
}
}
Here the log_admin
function log_admin($user,$pass)
{
$cek=$this->CI->db->where('admin_user',$user)
->where('admin_password',md5($pass))
->get('admin')
->row();
$row=count($cek);
if ($row==1) {
return $cek;
} else {
return false;
}
}
you can redirect the page from the controller, something like this.
after validating the user, it will redirect to your desired page.
function getlogin() {
$user = $this->input->post('username');
$pass = $this->input->post('password');
$user = $this->auth->log_admin($user,$pass);
if($user==true){
$this->session->set_userdata($user);
redirect('go to the next page');
}else{
$data['hasil'] = 0;
echo json_encode($data);
}
}

CodeIgniter Log Out Could still access the page after logging out when back button is clicked or typed a shortcut link

Hi Everyone i asking if how i can resolved this kind of problem. the problem is when i clicked the back button after logging out the user can still access the page or by typing the link of the page. i thought if i can destroy the session it will automatically disabled those pages..
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends MY_Controller {
public function index(){
$this->data['page_title'] = "User Login";
$this->load->view('templates/master', $this->data);
}
public function login(){
$username = $_POST['username'];
$password = $_POST['password'];
$data = $this->User_model->login ($username, $password);
if($data){
$this->session->set_userdata('users', $data);
$session_data = array(
'username' => $username);
$this->session->set_userdata($session_data);
redirect('users');
}
else{
$this->session->set_flashdata
('loginfail','<div class="alert alert-danger">×
<strong>Danger !</strong> Invalid Email or Password .</div>');
return redirect("auth");
}
}
public function logout()
{
$this->session->unset_userdata(array('username','id'));
$this->session->sess_destroy();
redirect('auth');
}
}
<a href="<?php echo ('auth/logout')?>" data-toggle="modal" data-target="#logoutModal">
<i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Logout
</a>
My Homepage controller Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends MY_Controller {
function __construct() {
if(empty($this->session->userdata('id'))){
redirect('auth/logout');
}
}
public function index()
{
$this->data['page_title'] = "Users List";
$this->data['users'] = $this->User_model->get();
$this->load->view('templates/master', $this->data);
}
public function add()
{
$this->data['page_title'] = "Add User";
$input_data = $this->input->post();
if(!empty($input_data))
{
$this->User_model->insert($input_data);
redirect('/users');
} else {
$this->load->view('templates/master', $this->data);
}
}
public function edit($id)
{
$this->data['page_title'] = "Edit User";
$input_data = $this->input->post();
if(!empty($input_data)){
$this->User_model->update($input_data);
redirect('/users');
} else {
$this->data['users'] = $this->User_model->get($id);
$this->load->view('templates/master', $this->data);
}
}
public function delete($id)
{
$this->User_model->delete($id);
redirect('/users');
}
}
My Core Controller Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $data;
public function __construct()
{
parent::__construct();
define('CONTROLLER', $this->router->fetch_class());
define('METHOD', $this->router->fetch_method());
}
}
Yes, you must log out of the user session. And you have to check the user session in the constructor of a controller.
Example:
class Users extends MY_Controller {
function __construct() {
if(empty($this->session->userdata())){
redirect('LOGIN_CONTROLLER');
}
}
}
logout and login works fine...
but you have to restrict or privilege your functions
example
public function isLoggedIn() {
if ($this->session->userdata('uId') == TRUE) {
return true;
} else {
return false;
}
}
public function index() {
$status = $this->session->userdata('uStatus');
if ($this->isLoggedIn() == TRUE && $status == "1") {
//your code here
} else {
$this->session->set_flashdata('error', 'You have to login first');
redirect('login');
}
}
You should redirect
if(empty($this->session->userdata('id'))){
redirect('LOGIN_CONTROLLER/METHOD_NAME_HERE');
}

CodeIgniter - How do I get session to detect whether user is logged in?

I have very simple page that requires login to view. I have a login controller and view that will redirect to the main page after successful login. However, i want to detect whether user is logged in if the user directly access the main page link, if not logged in, then the user should be redirect back to the login page.
My Login controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->view('login_view');
}
public function process()
{
$user = $this->input->post('user');
$pass = $this->input->post('pass');
if ($user=='admin' && $pass=='123')
{
$this->session->set_userdata(array('user'=>$user));
redirect("Report");
}
else{
$data['error'] = 'Your Account is Invalid';
$this->load->view('login_view', $data);
}
}
public function logout()
{
$this->session->unset_userdata('user');
redirect("Login");
}
}
?>
and my Login view:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<?php echo isset($error) ? $error : ''; ?>
<form method="post" action="<?php echo base_url('Login/process'); ?>">
<table cellpadding="2" cellspacing="2">
<tr>
<td><th>Username:</th></td>
<td><input type="text" name="user"></td>
</tr>
<tr>
<td><th>Password:</th></td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
while the login process is working good, but i'm not sure how to get the session from my main page to detect whether user is logged in. I know i should add some validation in the main controller but i'm not sure how, please help thank you.
main controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EstoreReport extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('ReportModel');
}
public function index()
{
$report=new ReportModel;
$data['data']=$report->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
You can create a function and call it to check whether the user is logged in or not
public function is_logged_in()
{
$user = $this->session->userdata('user_data');
return isset($user);
}
Assuming you have session helper autoloaded, just like validation on the Login controller, you could set the validation in the index method of the Main / Report controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class EstoreReport extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('ReportModel');
}
public function index()
{
if (!isset($this->session->userdata('user'))) {
redirect("Login");
} else {
$report=new ReportModel;
$data['data']=$report->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
}
You could use $this->session->has_userdata() as per CI docs
So
// Write a boolean returning method
/**
* Returns if there is a user session
*
* #return bool
*/
public function isLoggedIn()
{
return $this->session->has_userdata($some_defined_key_like_user_id);
}
...
// Then in your index controller method
/**
* Index controller method
*
* #return void
*/
public function index()
{
$this->isLoggedIn() ? $this->load()->view('login') : redirect("Report");
}
Just simple configure in your controller index():
Use $this->session->userdata('user') == NULL to check whether user is logged in
public function index()
{
if($this->session->userdata('user') == NULL)
{
redirect('Login');
}
else
{
$report=new ReportModel;
$data['data']=$orders->get_report();
$this->load->view('includes/header');
$this->load->view('Report/list',$data);
$this->load->view('includes/footer');
}
}
Try this
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('loginmodel', 'login');
$this->load->library('form_validation');
}
public function index() {
$this->load->view('admin/login');
}
// Check for user login process
public function user_aouth() {
$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->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
} else {
$username = $this->input->post('username');
$password = $this->input->post('password');
$data = array(
'username' => $username,
'password' => $password
);
if ($this->login->check_valid_user_details($data)) {
$session_data = array(
'username' => $username
);
$this->session->set_userdata($session_data);
//redirect to admin user dashboard
redirect('dashboard');
} else {
$this->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
}
}
}
public function logout() {
$this->session->unset_userdata('username');
$this->session->sess_destroy();
redirect('login');
}
}
In your login model
public function check_valid_user_details($data) {
$condition = "username=" . "'" . $data['username'] . "'" . "AND password=" . "'" . $data['password'] . "'";
$c = $this->db->select('*')
->from('admin')
->where($condition)
->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1) {
return $query->result();
} else {
return FALSE;
}
}
Use this at the top of every page under dashboard
if($this->session->userdata('username') == NULL){
redirect('login');
}
controller
public function index()
{
//redirect to dashboard
$this->dashboard();
}
public function dashboard()
{ //session wise operating isset session-> dashboard ,else login page
if ($this->session->userdata('userName')) {
//if user found
return $this->load->view('dashboard');
} else {
//if "no user found"
return $this->load->view('login');
}
}
public function login_check()
{ //functions retrives two values 1-user type 2-userId
$data['userdata'] = $this->Mdl_login->Login_check();
if ($data['userdata'] == false) {
$this->load->view('login', $data);
} else {
redirect(base_url('index.php/dashboard'), 'refresh');
}
}
function logout()
{ //session destroy function
$this->session->unset_userdata('userName');
redirect(base_url(), 'refresh');
}
Model
function Login_check()
{
$username = $this->input->post('UserName');
$password = $this->input->post("PassWord");
//check with your value
$this->db->where('userName', $username);
$this->db->where('password', $password);
$qry_getuserdata = $this->db->get('user_tbl');
if ($qry_getuserdata->num_rows() > 0) {
$result = $qry_getuserdata->result();
$userid = $result[0]->userId;
$usertype = $result[0]->userType;
$email = $result[0]->email;
$this->session->set_userdata('userName', $username);
$this->session->set_userdata('userId', $userid);
$this->session->set_userdata('userType', $usertype);
$this->session->set_userdata('email', $email);
return true;
} else {
return false;
}
}
Now you can access your session data anywhere
if(isset($_SESSION['userName'])){ $data['userName']= $_SESSION['userName']; }
You can have true or false from below function call, Call this function in your controller and then redirect as per the response.
$this->session->userdata( 'logged_in' );

Fatal error: Cannot redeclare class

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.

Displaying Database

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 {}

Categories