Codeigniter 2.1 - Call function in __construct - php

I am having following functions:
public function admin_login_check()
{
if($this->session->userdata('is_logged_in') == FALSE)
redirect('admin/admin_login');
}
and this one (for the moment):
public function index()
{
$this->admin_login_check();
$data['title'] = 'Početna | TOP';
$data['main_content'] = 'admin_home';
$data= $this->data + $data;
$this->load->view('admin/admin_template', $data);
}
public function admin_login()
{
$data['title'] = 'Prijava | TOP';
$data['main_content'] = 'admin_login';
$data= $this->data + $data;
$this->load->view('admin/admin_template', $data);
}
When I $this->admin_login_check() inside __construct function I get following error:
The web page at xxx/admin/admin_login has resulted in too many redirects.

The reason you are having too many redirects is because when you place
$this->admin_login_check();
inside your admin's constructor controller. This will always run on each method/function inside your admin controller.
And since you redirected to the same admin controller,
redirect('admin/admin_login');
It will check first if you're logged out, so it will try to redirect you again and again.
One solution is to actually separate your admin_login page on a separate controller. Maybe the home controller if you have that.

You can make one check for current method name as:
public function admin_login_check()
{
$loged_in = $this->session->userdata('is_logged_in') ? TRUE : FALSE;
if($this->router->method != 'admin_login' && $loged_in==FALSE)
redirect('admin/admin_login');
}
The IF checks if you are at any page except the admin_login page and you are not logged in.
How ever I think this method for redirecting is little wrong.
It will be a lot better if you make one function is_admin to return TRUE/FALSE and do something like this...
public function __construct()
{
parent::__construct();
if($this->is_admin() == FALSE && $this->router->method != 'admin_login')
redirect('admin/admin_login');
}
public function is_admin()
{
return $this->session->userdata('is_logged_in') ? TRUE : FALSE;
}

Related

codeigniter URL change

I am creating eCommerce in Codeigniter. Here is the controller file for registration:
class Register extends CI_Controller {
public function index()
{
$this->load->view('common/header');
$this->load->view('register');
$this->load->view('common/footer');
}
public function home(){
$this->load->view('common/header');
$this->load->view('common/slider');
$this->load->view('home');
$this->load->view('common/footer');
}
public function signup(){
$username = $this->input->post("username");
$password = $this->input->post("password");
$email = $this->input->post("email");
$this->form_validation->set_rules('username','User Name','required|is_unique[user.name]|min_length[4]');
$this->form_validation->set_rules('password','Password','required|min_length[5]');
$this->form_validation->set_rules('email','Email address','required|valid_email');
$this->form_validation->set_error_delimiters('<div class="text-danger">', '</div>');
if($this->form_validation->run() == true){
$this->load->model('register_model');
if($this->register_model->register_user($username,$password,$email)){
$this->home();
}else{
$this->index();
}
}else{
$this->index();
}
}
}
On form submit the page is redirecting to the home page but the URL on the browser is (http://localhost:8080/codignitor_projects/shophere/register/signup) But I want to change the URL to this (http://localhost:8080/codignitor_projects/shophere/)
I got your problem. I don't know your CI version. I hope you are using the latest one and I am also giving my answer according to the latest version CI-4.
Please Write
return redirect()->to('index');
or
return $this->response->redirect(base_url('YourControllerName/index'));
instead of
$this->index();
To clearify this problem I would like to give you an example. Let, I have a Test controller and there are two functions such as abc() and def()
class Test extends Controller
{
function abc()
{
echo "Hi ! I am ABC";
}
function def()
{
$this->abc();//URL will be: http://localhost/your_project_name/public/test/def
//return redirect()->to('abc'); //URL will be: http://localhost/your_project_name/public/test/abc
//return $this->response->redirect(base_url('Test/abc')); //URL will be:http://localhost/your_project_name/public/Test/abc
}
}
There are three lines inside the def() function that give you the same result but the URL from first one to others will be different which is commented.

Laravel 5 return redirect is not working as it should

I'm having a controller with some functions. In every function I get user data by sharing it from the Contoller.php
In controller.php
public function share_user_data() {
$user = Auth::user();
$this->checkValidation($user);
$this->user = $user;
View::share('user', $user);
}
public function checkValidation($user){
if($user->email_activated == 0){
var_dump($user->email_activated); // I get: int(0)
return redirect('/verifyEmail');
}
}
In the other controller
public function viewCategory(Category $category){
$this->share_user_data(); // here's the check
$this->get_site_lang();
$products = $category->products;
return view('category', compact('category','products'));
}
But I get the category view and not redirected to the verifyEmail route. How to fix this and why it's happening?
The controller function called by the route is the one responsible for the response. I guess it is viewCategory() in your example?
Your viewCategory() function is always returning view(). It must return redirect() instead. I think the main function should be responsible for picking the output of the request.
private function checkValidation($user) {
return $user->email_activated == 0;
}
public function viewCategory(Category $category) {
$user = Auth::user();
/* ... call to share_user_data() or whatever ... */
if ($this->checkValidation($user)) {
return redirect('/verifyEmail');
}
return view('category', compact('category','products'));
}

(Phalcon) How to redirect (Phalcon\Http\Response) from static method in model

I'm trying to create a reusable static function which redirects if true.
This function will be in a model.
public function checkEmtpy(ResultsetInterface $resultset)
{
$di = \Phalcon\DI::getDefault();
if (empty($resultset->toArray())) {
$di->get('flash')->error('Page not found.');
return $di->get('response')->redirect('content');
} else {
return false;
}
}
I tried several ways to redirect but I can't get it to redirect from the model.
What can I change to make this work or isn't this possible at all?
It is against MVC principle to do redirects in models. The redirect has to be done in the Controller. What you should do is return only the status from your model only. Something like this:
// Model
public function checkEmtpy(ResultsetInterface $resultset)
{
return empty($resultset->toArray());
}
// Controller
public action someAction()
{
$isEmpty = (new YourModelName)->checkEmtpy($someVariable);
if ($isEmpty === true) {
return $this->response->redirect(...);
}
}

How can I redirect when it gets the exception in Laravel?

In laravel ,how should I code the exception?
class DetailController extends Controller
{
public function index() {
$user_id = Request::get('id');
$user = User::find($user_id);
if($teacher) {
return view("detail",compact(["user"]));
}
return view("top");
// "Undefined variable: AAA (View:/Users/user2006734/lesson/lesson/resources/views/top.blade.php)"
}
}
When user_id is null,I want to make it redirect top page...
Using Route::redirect('/here', '/there', 301);
The Error does not occur but Redirected page is always blank.
check Request has parameter , if not then redirect or render different view
public function index() {
if(Request::has('id')){
$user_id = Request::get('id');
$user = User::find($user_id);
return view("detail", compact(["user"]));
}else{
return view("top");
}
}
Route::redirect('/here', '/there', 301); is for redirectiong routes via web.php.
In your controller use
return Redirect::route('home');
to redirect to the route named home

How do I display active record in codeigniter with multiple controllers?

I am building my comment module and trying to get the active records to display on view. Seems simple however I have a lot going on and using a separate model and controller then what the view is being generated from.
So I have a profile page ( where I'm trying to get the results to display )
Controller:
public function profile()
{
$this->load->helper('url'); //Include this line
$this->load->helper('date');
$this->load->library('session');
$this->load->library('form_validation');
$session_id = $this->session->userdata('id'); //Ensure that this session is valid
//TRYING TO MAKE A VARIABLE WITHT THE $_GET VALUE
$user_get = $this->uri->segment(3); // Modify this line
// LOAD THE CORRECT USER
$this->load->model('account_model');
$user = $this->account_model->user($user_get); //(suggestion) you want to pass the id here to filter your record
$data['user'] = $user;
$data['session_id'] = $session_id;
if($user_get != $user['id'] || !$user_get)
{
$data['main_content'] = 'account/notfound';
$this->load->view('includes/templates/profile_template', $data);
}
else
{
if($user_get == $session_id) //Modify this line also
{
$data['profile_icon'] = 'edit';
}
else
{
$data['profile_icon'] = 'profile';
}
$sharpie = $this->sharpie($user);
$data['sharpie'] = $sharpie;
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/profile_template', $data);
}
}
Now I have a new controller for my comments I'm trying to display:
public function airwave() {
$this->load->helper('date');
$this->load->library('session');
$airwave_get = $this->uri->segment(3);
$this->load->model('community_model');
$airwave = $this->coummunity_model->airwave($airwave_get);
$data['airwave'] = $airwave;
$data['main_content'] = 'account/profile';
$this->load->view('includes/templates/main_page_template', $data);
}
with this model:
public function airwave($id=null)
{
if(is_null($id)) {
$session = $this->session->userdata('is_logged_in');
$commenter_id = $this->session->userdata('id');
}else{
$commenter_id = intval($id);
}
$query = $this->db->query("SELECT * FROM airwaves_comments WHERE from_id=$commenter_id");
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data[0];
//above returns the single row you need to the controller as an array.
//to the $data['user'] variable.
}
}
and trying to display it on this view ( which is generated by the profile function )
<div class="profile_airwave_comment_text">
<?php echo $airwave['comment'];?>
</div>
I just can't seem to get it to pass the array variable I've created properly to that view?
thanks in advance.
The first glaring thing I see wrong is in you model's airwave function:
if($query->num_rows()==1)
{
$data = $query->result_array();
return $data[0];
You are assuming that there will only be one result in your query, so if there are more or less than one, your $data array will bever be set.
Also, even then you are only returning the first element in the array. I am not seeing anywhere in your question that you want to return only one.
Finally, in your view, if you now return the full array, and not only one element, you will have to do a foreach statement.
EDIT: please see suggested solution.
In your model, don't worry about the check for the amount of data in the result array. This will come later. Simply do:
return $query->result_array();
Now, keep your controller as is, but adapt your view:
<div class="profile_airwave_comment_text">
<?php
if (isset($airwave) && is_array($airwave) && !empty($airwave))
{
foreach ($airwave as $wave)
{
echo $wave['comment'];
}
}
else
{
echo 'No comments found...';
}
?>
</div>
This should work, and if not, at least let you know that no comments were fond, and thus check your database.
HTH!
If your using HMVC, simply call the module from inside the profile view, ie:
echo Modules::run('comments/profileComments', $user->id);
Else:
You would need to create a new method in the loader class, to load in the controller seperate from routing.
If your really after a quick fix until you come up with a better alternative, you could(depending if both controllers live in the same directory) just include the 'comments' controller in your 'profile' controller and try something like this:
{Cons: CI Pagination wont work!}
application/controllers/profile.php
include 'Comments' . EXT;
class Profile extends CI_Controller{
public function __construct ()
{
parent::__construct () ;
}
public function index( $user_id ){
$commentsPartialView = call_user_func_array(array(new Comments(), "getProfileComments"), array($user_id));
return $this->load->view($this->template, array(
'view' => 'profiles/_index',
'comments' => $commentsPartialView
));
}
}
-
application/controllers/Comments.php
class Comments extends CI_Controller{
public function __construct ()
{
parent::__construct () ;
}
public function getProfileComments( $user_id ){
$user_comments = ''; //pull from DB
//set third param to TRUE for partial view, without main template
return $this->load->view('comments/show', array(
'user_comments' => $user_comments
), TRUE);
}
}

Categories