Calling another controller within a controller if already logged in - codeigniter

I have a login controller, where I do a check wether he is logged in or not like so
if($logged_in){
$this->load->view('profile_view');
}
else{
$this->index();
}
Like you can see I'm loading a view if im not logged in. But instead of loading a view I'd rather have it that I load a controller that loads that view, because I want to send data from the controller to the view.
So I want to do something like this
if($logged_in){
$this->load->controller('profile_controller');
}
and in my profile controller put this
function index(){
$logged_in = $this->logged_in->is_logged_in();
if($logged_in){
$this->load->model('profile_model');
if($query = $this->profile_model->getAllUserInfo()){
$data['records'] = $query;
$this->load->view('profile_view', $data);
}
}
else{
echo "you don't have access on this page";
}
}
But It seems loading a controller from a controller isn't possible! So how can I create my view while sending data to it?

Take a look at how Ben Edmunds authentication library handles it.
if (!$this->ion_auth->logged_in())
{
redirect('auth/login');
}
Ion_Auth Lobrary - http://benedmunds.com/ion_auth/#logged_in

Related

How to access Model from Views in CodeIgniter

How to access Model from Views in Codeigniter.
I have a Model with a function, i need to call this function from view
Please Read the CI documentation First:
If You are using a MVC Structured Framework then you should be following the way it works.
You Need the Controller:
public function your_controller_function(){
// To load model
$this->load->model ('your_model');
//To Call model function form controller
$data = $this->your_model->model_function($ex_data);
//TO Send data to view
$this->load->view('your_view',['data'=>$data]);
}
Inside your model:
public function model_function($ex_data){
// Your Querys
// user return to send you query result to the controller anything
// Sample Example of query and return
$query = $this->db->select('*')
->where('your_column',$data['column_name'])
->get('your_table');
$your_result = $query->row_array();
if($this->db->affected_rows() > 0){
return your_result;
} else {
return FALSE;
}
}
Inside your view you can write :
<?php
$this->load->model('your_model');
$this->your_model->some_function();
?>
For example in User_controller load User Model $this->load->model('Users_model');
Then User View page $viewpage = this->Users_model->somefunction($id);

not able get flashdata in CodeIgniter

Here is my controller code
function index() {
echo $this->session->flashdata('message');
$this->load->view('categoryView');
}
function delete() {
$products = $this->item_model->get_category_id($category_id);
if (count($products)) {
$message = 'Category Name is used by the product. Please change them to another category!';
}
else {
$category_id = $this->product_category_model->delete($category_id);
$message = ($category_id) ? 'Category Deleted Successfully' : 'Failed to Delete Category';
}
$this->session->set_flashdata('message', $message);
redirect('category', 'refresh');
}
After calling the delete function the flashdata has to be set and retrieve that value in index() function of the same controller but I can't.
Am also tried the $this->session->keep_flashdata('message'); before redirect to index function. But still am not get any value in index function.
Also changed $config['sess_expire_on_close'] = FALSE; to $config['sess_expire_on_close'] = TRUE; Still am not get the result.
I am wasted more time(nearly half day). Please anybody help to retrieve the flas data in codeigniter.
There are several probabilities:
1- Check your browser cookie. See if it allows cookies or if any other extension is intervening.
2- Refresh might not send the browser a new request (which thus mean a new URL). Try it for another controller see if it make any change
3- hard code the set_flashdata() with hard-coded value than a variable. set_flashdata("message", "Thank you");
In codeingitor you cannot echo anything in controller.
You have to set in $this->session->flashdata('message'); in view file not in index() function of controller
Try again by putting $this->session->flashdata('message'); in "categoryView" file where you want to display flash message.
You could try:
function set_flashdata_notification($notify_type, $msg, $error_code = null)
{
$ci =& get_instance();
$flashdata_data = set_notification_array($notify_type, $msg, $error_code);
$ci->session->set_flashdata($flashdata_data);
}
function delete() {
$products = $this->item_model->get_category_id($category_id);
if (count($products)) {
set_flashdata_notification('Category Name is used by the product.','Please change them to another category!');
redirect('path_to_view/view','refresh');
}

codeigniter flow from controller to view is incorrect?

I have this code:
if(isset($result) && !empty($result))
{
if(is_string($result))
{
show_error('Failed to authenticate user with database');
$this->load->view('error', $result);
}elseif(is_object($result)){
show_error('ALL WENT OKAY!');
$this->load->view('valid', $result);
}
}
Now this code doesn't work as expected. Data is retrieved from database because if I do print_r($result) it will print the content which is correct. But when I have the above it doesn work. it just goes to index() method of my controller and does nothing. Another way I tried was:
$this->load->view('valid', $result);
without any if statements. it goes to authentication page but fails to print $result because it says undefined. any idea would be helpful.
Regards
Do it like this. Pass the result like this.
if($result)
{
$data['result'] = $result;
if(is_string($result))
{
show_error('Failed to authenticate user with database');
$this->load->view('error', $data);
}elseif(is_object($result)){
show_error('ALL WENT OKAY!');
$this->load->view('valid', $data);
}
}else{
$this->load->view('empty_view');
}
This should be suffecient to understand
$data['result'] = $result;
$this->load->view('valid', $data);

Securing View with codeigniter and IonAuth

I have setup Ion Auth for codeigniter 2.1.3.
All is working well.
In my controller, auth.php I have the below code for function index():
function index()
{
// if not logged in - go to home page
if (!$this->ion_auth->logged_in())
{
//redirect them to the login page
redirect('auth/login', 'refresh');
}
// if user is an admin go to this page
elseif ($this->ion_auth->is_admin())
{
echo "Admin User";
// if an admin, go to admin area
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
//list the users
$this->data['users'] = $this->ion_auth->users()->result();
foreach ($this->data['users'] as $k => $user)
{
$this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
}
$this->_render_page('auth/view_users', $this->data);
}
//if user is part of the master data team
elseif ($this->ion_auth->in_group("master_data"))
{
echo "master data group";
//redirect them to the master_data page
$data['title']="Master Data Home Page";
$this->load->view("site_header",$data);
$this->load->view("site_nav");
$this->load->view("content_master_data");
$this->load->view("site_footer");
}
elseif ($this->ion_auth->in_group("planning"))
{
echo "Planning";
//redirect them to the master_data page
$data['title']="IMS Planning";
$this->load->view("site_header",$data);
$this->load->view("site_nav");
$this->load->view("content_planning");
$this->load->view("site_footer");
}
else
{
echo "Generic user";
//redirect them to the default home page
$data['title']="IMS Home Page";
$this->load->view("site_header",$data);
$this->load->view("site_nav");
$this->load->view("content_home");
$this->load->view("site_footer");
}
}
My thought process is that the controller will only get loaded if their user is in the correct group. This works correctly and the correct view is loaded for each user. My problem is that I can still browse directly to any view, for example http://localhost/logico/application/views/content_master_data.php
How do I restrict access to the view / controller so that the page cannot be accessed by someone who is not logged in and someone that is not in the correct group.
Instead of loading different views u must redirect each user group to different controller.
Auth index
function index()
{
// if not logged in - go to home page
if (!$this->ion_auth->logged_in())
{
//redirect them to the login page
redirect('auth/login', 'refresh');
}
// if user is an admin go to this page
elseif ($this->ion_auth->is_admin())
{
echo "Admin User";
// if an admin, go to admin area
//set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
//list the users
$this->data['users'] = $this->ion_auth->users()->result();
foreach ($this->data['users'] as $k => $user)
{
$this->data['users'][$k]->groups = $this->ion_auth->get_users_groups($user->id)->result();
}
$this->_render_page('auth/view_users', $this->data);
}
//if user is part of the master data team
elseif ($this->ion_auth->in_group("master_data"))
{
//redirect them to the master controller
redirect('master','refresh');
}
elseif ($this->ion_auth->in_group("planning"))
{
//redirect them to the planning controller
redirect('planning',refresh);
}
else
{
//redirect them to the generic controller
redirect('generic','refresh');
}
}
Master Controller
class Master extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->ion_auth->in_group('master_data'))
{
redirect('auth/login', 'refresh');
}
}
function index()
{
$data['title']="Master Data Home Page";
$this->load->view("site_header",$data);
$this->load->view("site_nav");
$this->load->view("content_master_data");
$this->load->view("site_footer");
}
}
Similarily planning and generic controller's constructor must contain the corresponding authentication check.This will prevent unwanted method execution through url .

Codeigniter mobile redirect with caching

I have got my site(mysite.com) to redirect to mysite.com/Mobile for mobile browsers using codeigniters useragent library from my default controller.
When I cache my output from the controller the redirect doesnt work as the browser is served the cached file.
Is there a proper way to go about redirecting from the config/routes.php file? Will this redirect mobile visitors?
My controller
class Child extends Controller {
function child()
{
parent::Controller();
//$this->output->cache(7200);
$agent = $this->agent->browser() . ' ver ' . $this->agent->version();
}
function index()
{
if ($this->agent->is_mobile())
{
header('Location: ' . site_url() . 'Mobile/', TRUE, 301);
exit(0);
}else{
$this->output->cache(7200);
$this->load->view('home',$data);
}
}
I wouldn't suggest using CodeIgniter's output caching. That runs before the Controller, therefore you will never get in the index(). Routing can't deal with this situation as it isn't able to detect if the client is mobile.
It's a better idea to use the other caching method that CodeIgniter offers, as it's more granular, you can cache the single views. http://codeigniter.com/user_guide/libraries/caching.html
function index()
{
// should put this in the __construct() of this controller or in your MY_Controller.php
$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
if ($this->agent->is_mobile())
{
redirect('Mobile');
}
else
{
// if this doesn't get us the output, recreate and store it
if(!$output = $this->cache->get('controllername_index_output'))
{
$output = $this->load->view('home', $data, TRUE);
$this->cache->save('controllername_index_output', $output, 7200);
}
// now we surely have the output ready, whether it was cached or not
$this->output->set_output($output);
}
}

Resources