redirect is not working in codeigniter _construct function - codeigniter

I am facing a problem using redirect in _construct function,
In timesheet controller I wrote the following code and I am getting an error in the browser "
This problem can sometimes be caused by disabling or refusing to
accept
cookies.
Here is my code
class Timesheet extends MY_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('timesheet_model');
//$this->load->library('auth');
$username=$this->session->userdata('logged_in');
//$this->load->model('login_model');
if($username['fullname']!=""){
redirect('timesheet');
}
else{
redirect('login');
}
}
Please help me to find a way to get rid of this problem.
Thanks.

It looks to me like you're going around in a loop.
You check to see if the fullname element in your $username array is empty and, if it is, you redirect back to the same controller. I'm willing to bet it goes around in a circle like that for a while before the webserver throws up the error you mention.
If I'm reading what you're trying to do correctly, wouldn't you call another function within your Timesheet constructor if the fullname element is present to show whatever information it is that you're trying to display?
I'd suggest changing your logic to do the following:
if($username['fullname'] == ""){
redirect('login');
}
else{
//go to another controller method here
}

OK. I got it. The error is just because of I am redirecting to same controller where I have written the code. Everytime when it redirects to timesheet it enters into the construct function and it redirects again to timesheet. And the same thing is working like an endless loop.
So the fault was redirecting to the same controller.
I

use redirect like this : redirect('timesheet', 'refresh');

Related

CodeIgniter URI Routing: remove method name index from URL

I am working with CodeIgniter (V:2.2.6) and I have a simple class User with some basic methods like create, update, edit, delete and index. For the index function, I am using an argument $user (which is the second URI segment) in order to display some information regarding that user. So the default URL looks like:
/user/index/john
to display some information about the user 'john'.
Now, I want to remove the term 'index' from the URL, so that it looks like:
/user/john
For that purpose I have added the following rule in routes.php.
$route['user/(:any)'] = "user/index/$1";
It serves the purpose, but it prevents accessing other functions like /user/create and goes inside /user/index automatically. To solve this problem, I can not see any other way except manually adding routing rules like
$route['user/create'] = "user/create";
for each method of the User class, which is not cool at all. So, please can anyone suggest me a better way of routing under the current circumstances?
Here are my codes:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function index($user = '') {
echo "index!";
}
public function create() {
echo 'create!';
}
}
Note: I have gone through the CodeIgniter documentation for URI Routing and another similar question here, but could not figure out a promising solution. And please don't suggest for CodeIgniter version update.
I'm not sure, if this is the answer you like, but i think it should work.
Just put this function in your user controller.
public function _remap($method)
{
if (method_exists($this, $method))
{
$this->$method();
}
else
{
$this->index($method);
}
}

How do i redirect to a page from php yii2.0 components?

I Have a component ,in which have one init() function which is to be called before each action.
I only need to check if the session is expired redirect the user to login.
Here is my code,
config/main.php coponents -
'MyGlobalClass'=>[
'class'=>'common\components\MyGlobalClass'
],
and
'bootstrap' => ['log','MyGlobalClass'],
components/MyGlobalClass .php :
class MyGlobalClass extends \yii\base\Component{
public function init() {
//echo "Hi";
if(Yii::$app->user->isGuest)
{
//echo 'called';exit;
Yii::$app->getResponse()->redirect(Yii::$app->urlManager->createUrl('login'));
}
//parent::init();
}
}
so it is coming inside if{} but not redirecting to login page.
You can try this, it worked for me:
return Yii::$app->getResponse()->redirect('admin/page/signin');
You may use this to send your response
Yii::$app->response->send();
but please review the guide for controller/action distinct access control
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
You can try the code below:
Yii::$app->getResponse()->redirect(Yii::$app->urlManager->createUrl('login'));
return;
correct way is :
Yii::$app->response->redirect(Yii::$app->urlManager->createAbsoluteUrl('site/logout'));
return;
This way you'll get an infinite redirect loop: The component is called on each controller call, redirection will never stop.
Better to manage it from public function behaviors() on each controller, check the Authorization section on Yii2 documentation.
May be this one help you :)
return Yii::$app->getResponse()->redirect(['user/login']);
or
return Yii::$app->getResponse()->redirect(Yii::$app->urlManager->createUrl('user/login'));

Laravel 4 route-model binding exceptions doesn't work despite docs and examples

I read a lot about Laravel4 Route-model binding (L4 docs, tutorials, etc.) but still exceptions (i.e. the model is not found) don't work for me
These are my basic files
routes.php:
Route::model('game', 'Game', function(){
// override default 404 behavior if model not found, see Laravel docs
return Redirect::to('/games');
});
...
Route::get('/games/edit/{game}', 'GamesController#edit');
GamesController.php
class GamesController extends BaseController {
...
public function edit(Game $game){
return View::make('/games/edit', compact('game'));
}
}
Pretty straight, but I get this error: Argument 1 passed to GamesController::edit() must be an instance of Game, instance of Illuminate\Http\RedirectResponse given
If I type http://mysite.dev/games/edit/1 all is fine (model with ID = 1 exists)
If I type http://mysite.dev/games/edit/12345 (no model with that ID) the ugly error above is triggered instead of the redirect I specified
I also looked at this (the bottom part where a Redirect closure is suggested: that is just what I am doing!) but no way to make it work: laravel 4 handle not found in Route::model
What's wrong with it? Please any help?
Thanks in advance
In Route::model you declare which variable will be a model instance, you shouldn't use it to do a redirection that way. Instead of that, specify that $game is of type Game and then work with your routes:
Route::model('game', 'Game');
...
Route::get('/games/edit/{game}', 'GamesController#edit');
Then if you access to /games/edit/3 GamesController::edit will receive an instance of Game class whose id=3
I ended up by setting a general "Not Found" error catcher, like this:
// routes.php
App::error(function(Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
return Response::make('Not Found', 404);
});
...
Route::model('game', 'Game');
...
Route::get('/games/edit/{game}', 'GamesController#edit');
What I understand is that if I want a custom redirect and not a general 404 page (i.e. take the user to games' list if model not found), I CAN'T use the route-model-binding
In other words, I have to use Route::get('/games/edit/{id}', 'GamesController#edit'); and then do my application logic inside the 'edit' method:
public function edit($id){
$game = Game::findOrFail($id);
// if fails then redirect to custom page, else go on saving
}
I'm very new to Laravel, but as far as I can see this has nothing to do with the closure, but with the use of "Redirect::to" inside that closure. Using "App::abort( 404 );" works.

Laravel 4: redirect if item doesn't exists, ModelNotFoundException doesn't work anyway I try it

I'm following Dayle Rees' book "Code Bright" tutorial on building a basic app with Laravel (Playstation Game Collection).
So far so good, the app is working but, following his advices at the end of the chapter, I'm doing my homeworks trying to improve it
So, this snippet is working fine for existing models but throws an error if the item doesn't exists:
public function edit(Game $game){
return View::make('/games/edit', compact('game'));
}
In other words, http://laravel/games/edit/1 shows the item with ID = 1, but http://laravel/games/edit/21456 throws an error since there's no item with that ID
Let's improve this behaviour, adapting some scripts found also here on StackOverflow (Laravel 4: using controller to redirect page if post does not exist - tried but failed so far):
use Illuminate\Database\Eloquent\ModelNotFoundException; // top of the page
...
public function edit(Game $game){
try {
$current = Game::findOrFail($game->id);
return View::make('/games/edit', compact('game'));
} catch(ModelNotFoundException $e) {
return Redirect::action('GamesController#index');
}
}
Well... nothing happens! I still have the error with no redirect to the action 'GamesController#index'... and please notice that I have no namespaces in my Controller
I tried almost anything:
Replace catch(ModelNotFoundException $e) with catch(Illuminate\Database\Eloquent\ModelNotFoundException $e): no way
put use Illuminate\Database\Eloquent\ModelNotFoundException; in Model instead of Controller
Return a simple return 'fail'; instead of return Redirect::action('GamesController#index'); to see if the problem lies there
Put almost everywhere this snippet suggested in Laravel documentation
App::error(function(ModelNotFoundException $e)
{
return Response::make('Not Found', 404);
});
Well, simply nothing happened: my error is still there
Wanna see it? Here are the first two items in the errors stack:
http://www.iwstudio.it/laravelerrors/01.png
http://www.iwstudio.it/laravelerrors/02.png
Please, can someone tell me what am I missing? This is driving me mad...
Thanks in advance!
Here are few of my solutions:
First Solution
The most straightforward fix to your problem will be to use ->find() instead of ->findOrFail().
public function edit(Game $game){
// Using find will return NULL if not found instead of throwing exception
$current = Game::find($game->id);
// If NOT NULL, show view, ELSE Redirect away
return $current ? View::make('/games/edit', compact('game')) : Redirect::action('GamesController#index');
}
Second solution
As I notice you may have been using model binding to your route, according to Laravel Route model binding:
Note: If a matching model instance is not found in the database, a 404 error will be thrown.
So somewhere where you define the model binding, you can add your closure to handle the error:
Route::model('game', 'Game', function()
{
return Redirect::action('GamesController#index');
});
Third Solution
In your screenshot, your App::error seems to work as the error says HttpNotFound Exception which is Laravel's way of saying 404 error. So the last solution is to write your redirect there, though this apply globally (so highly discouraged).

missing login page when redirect

i was create codeigniter controller like this :
function Home() {
parent::Controller();
if(!$this->session->userdata('id'))
redirect ('login');
$this->load->model('Home_Model');
}
but when i try to access the page, the redirect page now show. just show 404 not found but i was create login.php on controller and views also home_model.php on model.
what the problem with that code and how to fix that?
thank you
Because of this line: parent::Controller(), I assume that you are using CodeIgniter 1. Since you are building pages like home and login, I assume that you are starting building a new website. If my assumptions are right, I suggest you using the latest CodeIgniter (v2.1.0 at the moment, required PHP 5.1.6 or newer). You can grab a copy at CodeIgniter Home Page.
First of all, I think you should check your error reporting level. It should be something like error_reporting(E_ALL); for debugging. If not yet, turn it on and run the code again. Maybe you will get your own answer after that :)
After that, you should try the code below for your constructor to check that your home controller process as you expected.
function Home()
{
parent::Controller();
echo 'Home Class Initialized';
}
It should at least show 404 page. If it doesn't print out anything then we need more information. Maybe you should turn on logging and analyze your log files: look for /application/config/config.php: $config['log_threshold'] = 2;
If it print out 'Home Class Initialized' follow by a 404 message: please check if your controller have something like:
public function index()
{
echo 'Invoke default method';
}
If not yet, please add one. You may also want to take a look at using your own default method here
If it still a 404 then sorry, I have no idea. Maybe you should post more code.
If it print out 'Home Class Initialized' only: good. Now try this
function Home()
{
parent::Controller();
if ( ! $this->session->userdata('id'))
{
echo 'Redirecting to login page';
//redirect ('login');
}
$this->load->model('Home_Model');
}
If this print out Redirecting to login page, it's now time for you to uncomment //redirect ('login'); and check the login page. Follow the same path with step 1 & 2.
If not, check your session data: var_dump($this->session->userdata('id'). You could learn more about PHP falsehood here
After all, if it still fails, consider using __construct() of PHP 5
function __construct()
{
parent::__construct();
if ( ! $this->session->userdata('id'))
{
redirect ('login');
}
$this->load->model('Home_Model');
}
Other: if you use this $this->load->model('Home_Model');, I think you will have to call home_model like this $this->Home_Model->foo(); or there will be error access to NULL

Resources