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

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

Related

Laravel - Action not defined but it is defined

I get this error when i try loading blade.php
Action App\Http\Controllers\InventoryItemController#change not defined.
I have change function in InventoryItemController
public function change($new_status)
{
//
}
This started when I wanted to make button
Confirm Change
I did everything same when i made Edit button and that button works normally.
UPDATE 1
My button looks like this now
<a href="{{route('change', [$inventoryitem['new_status'],
$inventoryitem['asset_id']])}}"class="btn btn-info">Confirm Change</a>
and my change function is this
public function change($new_status, $asset_id)
{
$asset = Asset::find($asset_id);
$asset->status = $new_status;
return redirect('showasset', compact('asset','asset_id'));
}
and my route in web is like this
Route::get('change/{$new_status}/{$asset_id}','InventoryItemController#change')->name('change');
But after i click button it just redirect me to url .../change/4/1 and that's it. Nothing changes.
Using Action is deprecated in Laravel
You can use routes instead.
Define Routes in your routes files (/routes/web.php) like.
Route::get('change/{status}','InventoryItemController#change')->name('change');
and then in your view
Confirm Change
In your controller use.
public function change ($status){
// rest of the function.
}
Hope this helps
Define your controller's method in route file as following:
Route::get('url/{new_status}',InventoryItemController#change);
Answer on UPDATE 1
public function change($new_status, $asset_id)
{
$asset = Asset::find($asset_id);
$asset->status = $new_status;
$asset->save();
return view('your_view_path',compact('variable1','variable2'));
}
Final error was in my route
Route::get('change/{$new_status}/{$asset_id}','InventoryItemController#change')->name('change');
It should be like this
Route::get('change/{new_status}/{asset_id}','InventoryItemController#change')->name('change');
After that change everything is working flawlessly. Thank you for your help guys!

redirect is not working in codeigniter _construct function

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

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

Codeigniter Sessions Checking from a header view file

I am fairly new and just started to use Codeigniter, and have come across some confusion regarding sessions.
What I want to achieve is, like in regular php, I want to check if a user is logged in by using a header include file which checks the session data. I dont want to check/write that checking code in every controller while passing data to the view file.
Can someone please show me how it can be done?
Ex. I don't want to do the following in every controller:
//Controller:
if($this->session->userdata('loggedin'){
$data['loggedin'] = $this->session->userdata('loggedin');
}
//I dont want to check the above on every function in every controller
$this->load->view('some_view_file', $data);
//some_view_file
if(isset($loggedin)){
echo "You are logged in!";
}
else
{
echo "Please log in!";
}
Instead, I want something to like the following:
//some view file
if(isset($loggedin))
{
echo "your logged in";
}
else
{
echo "please log in";
}
And also, how can I use native php sessions instead of CI Sessions. Any help will be much appreciated. Thanks.
Firstly, theres no reason you can't just write something like this in your view:
<? echo ($this->session->userdata('loggedin')) ? "Logged In": "Not Logged In"; ?>
Then your controllers don't need any of that code.
However if the check is more complex or something, then theres a few places you can do it.
1) In the constructor of a custom controller: create a new file application/core/MY_Controller.php, and override the constructor with something like:
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
if($this->session->userdata("loggedin")) {
// do something
}
}
}
then make all your controllers extend MY_Controller.
2) Or in a post_controller_constructor hook. http://codeigniter.com/user_guide/general/hooks.html (this is more transparent, and probably easier if you have tons of controllers already)
You can use native sessions with this:
http://codeigniter.com/wiki/Native_session/
I think using a construct on your controller would be the smartest approach.
I also recommend encrypting your session cookie.
class Blog extends CI_Controller {
public function __construct()
{
parent::__construct();
//always check if session userdata value "logged_in" is not true
if(!$this->session->userdata("logged_in"))
{
redirect('login');
}
}
}

How to prevent to direct link access in Code igniter

How to prevent to direct link access in Code igniter
E.g.
http://localhost/myapp/admin/displayUser
There is no built in authentication library within CodeIgniter, although there are many well developed third party ones. My preference is for Ion Auth - http://benedmunds.com/ion_auth/.
However if you are simply referring to preventing access to some "private" controller methods, you should add an underscore to the beginning of the method name - this will mean it is not accessible via a url, only via other controller methods:
function _myprivatemethod() {
return true;
}
Create a library as authenticate.php having following code into it and add that library in autoload.php
class Authenticate
{
function Authenticate()
{
$CI = & get_instance();
if ($CI->session->userdata('USERID') == "")
{
$redirectlink = 'contoller function path to your login page';
redirect($redirectlink);
exit;
}
}
}
This my not help you but it might help someone else.
I did it by creating a hook that checks if the user is logged in . If they are not it redirects them to the home login controller.
if (!$this->session->userdata('logged_in')) {
redirect('user/login');
}
If you create a Auth_Controller that extends CI Controller then instead of extending CI Controller you can make all your apps extend your new Auth_Controller so they always redirect if the user is not logged in.
if (!$this->session->userdata('logged_in')) {
redirect('user/login');
}
this will perfectly work..
just remember to load the session library as well.
$this->load->library('session');

Resources