Codeigniter redirect method is not working - codeigniter

This is my User.php controller
I am unable to use redirect method.
i am working on xampp localhost
?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->load->library('Admin_layout');
$this->config->load('reg_rules');
$this->load->model('admin/user_model');
$this->load->helper('form');
$this->load->helper('url');
}
public function index()
{
if (!$this->auth->loggedin()) {
redirect('admin/login');
}
}
public function add(){
//if($this->input->post('submit')){
$this->form_validation->set_rules($this->config->item('reg_settings'));
$data["reg_attrib"] = $this->config->item("reg_attribute");
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run('submit') == FALSE)
{
// templating
$this->admin_layout->set_title('Add a User');
$this->admin_layout->view('admin/add_user',$data["reg_attrib"]);
// templating
}
else
{
// Develop the array of post data and send to the model.
$passw = $this->input->post('password');
$hashpassword = $this->hash($passw);
$user_data = array(
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'phone' => $this->input->post('contact_no'),
'email' => $this->input->post('email'),
'password' => $this->hash($hashpassword),
'doj' => time(),
);
$user_id = $this->user_model->create_user($user_data);
Here i am setting my success message using set_flashdata
and redirecting
if($user_id){
$this->session->set_flashdata('item', 'Record created successfully');
$this->redirect('admin/user/add','refresh');
}else{
echo "User Registration Failed!";
}
}//else
//} // submit
} // add
}
View_users.php
<?php
if($this->session->flashdata('item'))
{
echo $message = $this->session->flashdata('item');
}
?>
I am getting the following error
Fatal error: Call to undefined method User::redirect() in C:\xampp\htdocs\ci\application\controllers\admin\User.php on line 67
A PHP Error was encountered
Severity: Error
Message: Call to undefined method User::redirect()
Filename: admin/User.php
Line Number: 67
Backtrace:

Try to change from
$this->redirect('admin/user/add','refresh');
to
redirect('admin/user/add','refresh');
Hope it will be useful for you.

Related

An uncaught Exception was encountered. Call to undefined method Admin_model

Okay i've cloned a codeigniter code copy and use it to designed a app, recently i wanted to start a new app and did opened the downloaded copy again and started to program, but now i am getting the the above mentioned error, this code worked in my prevouis code but in this it isn't.
An uncaught Exception was encountered
Type: Error
Message: Call to undefined method Admin_model::get_stock_item()
Filename: C:\xampp\htdocs\francois\application\controllers\Admin.php
Line Number: 239
Here is my controller
///<?php
if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class Admin extends CI_Controller {
public function __Construct() {
parent::__Construct();
if(!$this->session->userdata('logged_in')) {
redirect(base_url());
}
$this->load->model('Admin_model');
}
function stock_adjustment($id)
{
$data = array(
'formTitle' => 'Stock Management',
'title' => 'Stock Management'
);
$data["data"] = $this->Admin_model->get_stock_item('', '', $id);
$this->load->view('frame/header_view');
$this->load->view('frame/sidebar_nav_view');
$this->load->view('stock/update_price', $data);
$this->Admin_model->Update_asset($id);
redirect( base_url('stock/stock_view'));
}
}
Model
///function get_stock_item($limit, $start, $id=0)
{
///if(empty($id)){
///$this->db->limit($limit, $start);
///$query = $this->db->get('tbl_stock');
///if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
///return $data;
}
/// return false;
///} else {
///$query = $this->db->get_where('tbl_stock', array('id' => $id));
///return $query->row_array();
}
}
Please as i said it worked in my othered app but not in this one code is exaclty the same.
The error message is quite clear: The class Admin_model does not have a method named get_stock_item(). Probably beause you have commented-out the definition of the method.
Change the line
///function get_stock_item($limit, $start, $id=0)
to
function get_stock_item($limit, $start, $id=0)
There's a lot of other code that is commented and, as it stands, I think you will get lots of other errors running that model method.

Hooks in login page gives error localhost redirected you too many times

I am getting error -
localhost redirected you too many times.
in hooks
This is my code in hooks.I am unable to resolve this issue please help me
and please explain how to use hooks in ci and i am using post_controller_constructor
<?php
class Example {
private $CI;
function __construct()
{
$this->CI =& get_instance();
if(!isset($this->CI->session)){ //Check if session lib is loaded or not
$this->CI->load->library('session'); //If not loaded, then load it here
}
//echo "class".$this->CI->router->class; die;
if ( $this->CI->router->class == 'student' )
{
return;
}
}
public function check_login()
{
echo $session_userdata = $this->CI->session->userdata('email');
echo "session data".$session_userdata;
// die;
if(empty($session_userdata)) {
redirect("student/index");
}
else {
echo "here";
}
}
}
?>
i'm guessing your hook array looks like
$hook['post_controller_constructor'] = array(
array(
'class' => 'Example',
'function' => 'check_login',
'filename' => 'Example.php',
'filepath' => 'hooks'
),
);
It doesn't really matter whether you return anything in your constructor or not - a constructor serves only one purpose - to instantiate their respective class.
So basically you have to do something like
class Example {
private $CI;
function __construct()
{
$this->CI =& get_instance();
if(!isset($this->CI->session)){ //Check if session lib is loaded or not
$this->CI->load->library('session'); //If not loaded, then load it here
}
}
public function check_login()
{
echo $session_userdata = $this->CI->session->userdata('email');
echo "session data".$session_userdata;
// die;
if(empty($session_userdata) && $this->CI->router->class !== 'student') {
redirect("student/index");
}
else {
echo "here";
}
}
}
First of all, if you are using hooks in the CodeIgniter for the first time then follow some steps.
Step1: Enabling Hooks
The hooks feature can be globally enabled in the application/config/config.php file
Open config.php file does following replaces
$config['enable_hooks'] = FALSE;
To
$config['enable_hooks'] = TRUE;
Step2: Defining a Hook
Hooks are defined in the application/config/hooks.php file.
$hook['post_controller'] = array(
'class' => 'firstHookFile',
'function' => 'checkHook',
'filename' => 'firstHookFile.php',
'filepath' => 'hooks'
);
Step3: Create hook file
Create file in the application/hooks.
<?php
class firstHookFile
{
public function checkHook()
{
// load the instance
$this->CI =& get_instance();
$this->CI->load->helper('uri');
echo base_url();
return;
}
}
?>
This hook is only for example purpose, this hook will return the base URL of your project.
I hope you have understood how to use hooks in Codeigniter.

How to get base url in pre_controller hook in codeigniter

I am working on hook file, i am using pre_controller function of hook, but when i tried to use base_url() function in it, it is not working for me, it give me this error Call to undefined function base_url(), can anyone please help me to resolve this error ? here i have added my whole function
$hook['pre_controller'] = function()
{
$this->CI = get_instance();
$ci =& get_instance();
$router =& load_class('Router', 'core','uri','url');
$controller_name = $router->fetch_class();
$action_name = $router->fetch_method();
$segement = $router->uri->segment(2);
echo base_url(); die;
try {
$rc = new ReflectionClass($controller_name);
} catch (Exception $ex) {
if($segement == "") {
echo base_url(); die;
//header("Location:".$controller_name.'/overview');
//redirect($controller_name.'/overview');
//exit;
}
}
};
This won't work because base_url() gets initialized if a Controller is loaded.
And pre_controller basically means the opposite.
There are two options for you
Option 1
create a PreControllerHook.php in your application/hooks/ directory.
class PreControllerHook extends CI_Controller
{
public function initialize()
{
$controller_name = $this->router->fetch_class();
//... and so on
}
}
Setup your hooks.php config
$hook['pre_controller'] = [
[
'class' => 'PreControllerHook',
'function' => 'initialize',
'filename' => 'PreControllerHook.php',
'filepath' => 'hooks'
[
];
Option 2
create a PostControllerConstructorHook.php in your application/hooks/ directory.
class PostControllerConstructorHook
{
public function initialize()
{
$ci = get_instance();
$controller_name = $ci->router->fetch_class();
//... and so on
}
}
Setup your hooks.php config
$hook['post_controller_constructor'] = [
[
'class' => 'PostControllerConstructorHook',
'function' => 'initialize',
'filename' => 'PostControllerConstructorHook.php',
'filepath' => 'hooks'
[
];
You can find more information on their official documentation page here.
i hope this will work for you
base_url() function not working in codeigniter

An uncaught Exception was encountered in hmvc

An uncaught Exception was encountered
Type: Error
Message: Call to undefined method MY_Loader::_ci_object_to_array()
Filename: C:\xampp\htdocs\hhh\application\third_party\MX\Loader.php
Line Number: 300
Try this. Add it in the MY_Loader.
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
/* load the MX_Loader class */
require APPPATH."third_party/MX/Loader.php";
class MY_Loader extends MX_Loader
{
/** Load a module view **/
public function view($view, $vars = array(), $return = FALSE)
{
list($path, $_view) = Modules::find($view, $this->_module, 'views/');
if ($path != FALSE)
{
$this->_ci_view_paths = array($path => TRUE) + $this->_ci_view_paths;
$view = $_view;
}
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => ((method_exists($this,'_ci_object_to_array')) ? $this->_ci_object_to_array($vars) : $this->_ci_prepare_view_vars($vars)), '_ci_return' => $return));
}
}

Is it possible to have global class variables in CodeIgniter?

I am developing an application in CodeIgniter that has a member login system. I have a model that gets all the information of a requested member.
class Member extends CI_Model {
var $info = array();
var $error = NULL;
function __construct(){
parent::__construct();
}
public function get_info($member_id = ''){
$this->db->where('member_id', $member_id);
$this->db->limit(1);
$query = $this->db->get('members');
if($query->num_rows() > 0){
$member = $query->row_array();
$info = array(
'id' => $member['member_id'],
'display_name' => $member['display_name'],
'email_address' => $member['email_address'],
'password' => $member['password'],
'status' => ($member['status'] == 0) ? FALSE : TRUE,
'activation_code' => $member['activation_code'],
'location' => $member['location'],
'date_joined' => date('M jS, Y', $member['date_joined']),
'gender' => ($member['gender'] == 0) ? 'Male' : 'Female',
'results_per_page' => $member['results_per_page'],
'admin_emails' => ($member['admin_emails'] == 0) ? FALSE : TRUE,
'member_emails' => ($member['member_emails'] == 0) ? FALSE : TRUE
);
$this->info = $info;
} else {
$this->error = 'The member you requested could not be found in our database.';
}
}
At the top of my controllers and other models, I use the following to get the information of the current user to pass it along to all of the methods.
function __construct(){
parent::__construct();
$this->member->get_info($this->session->userdata('member_id'));
$this->user = $this->member->info;
}
function index(){
if($this->user['id'] > 0){
echo "You are logged in!";
} else {
echo "You are NOT logged in!";
}
}
Is there a way to do this on a global scale? It's kind of tiresome to type out the construct code at the top of every controller.
So I managed to find another post here on StackOverflow that solved my problem.
enter link description here
In application/core, I extended the existing Controller and Model classes with a few additions. Then I had to change my controllers and models to suit.
class Home extends MY_Controller {
}
application/core/MY_Model.php
class MY_Model extends CI_Model {
var $user = array();
function __construct(){
parent::__construct();
$this->load->model('member');
$this->member->get_info($this->session->userdata('member_id'));
$this->user = $this->member->info;
}
}
application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
var $user = array();
function __construct(){
parent::__construct();
$this->load->model('member');
$this->member->get_info($this->session->userdata('member_id'));
$this->user = $this->member->info;
}
}
In construct simply try to access session data
function __construct() {
if($this->session->userdata('member_id')) {
echo 'You are logged in';
} else {
echo 'You are not logged in';
}
}
It is simple rather than getting all the data and selecting 'user id',if we check whether ths session data is there then a user is logged in orelse no one is logged.You can add this at your each controller construct function and you can check without help of any DB

Resources