Is there somewhere in codeigniter where I could configure an automatic redirect to my root page if the user's session is expired (I am not trying to extend the session expiration's time)?
Situational example:
User logs in, leaves page idle for one day, returns to page that
requires validated session and sees PHP errors everywhere.
I'd prefer for anything in this situation to be redirected to my root login page.
Thank you!
Use below code in each function and place your function code inside the if loop. This will be use full for you. Thank you .
$this->load->helper('url');
if($this->session->userdata('logged_in'))
{
// You function code should be placed here .
}
else{
redirect(site_url(),'refresh');
}
put this content into your constructor function because when the controller run constructor will execute first.
function __construct() {
parent::__construct();
if(empty($this->session->userdata("login_session_user")))
{
redirect(site_url(),'refresh');
}
}
Related
Can I redirect to the previous page someone if not logged in? Also, is it possible to create a hierarchy system for users?
I tried this:
if(!(Auth::check())) {
header("Location: {{ route('cooperado.index') }});
}
But i not even got an error message, just doesn't work. I'm starting at laravel so it's kind of hard to fully understand how it works.
Using Constructor in controller
You also can use middleware in order to redirect unauthenticated user back or somewhere else.
public method __construct(){
$this->middleware('auth');
}
Add this code in your controller so all methods within particular controller
-direct from route defination
Route::get('/path/',controller#method)->name('cooperado.index')->middleware('auth');
Redirection
using this method unauthenticated user will redirect to login page.
in order to edit redirection page you can change '#redirectTo' method
in
app/Http/Middleware/Authenticate.php
file.
if(!(Auth::check())) {
return redirect()->route('cooperado.index');
}
You mention in your question also wants to return previous page then use following but i'm not recommended this because if your first login effort fails then login failed' page becomes your previous page and second login effort succeeds then you are redirected to login page again because it's your previous page.
return Redirect::to(URL::previous());
You can use this. Is the easiest way to do this.
And you can also pass message, will displayed on when user redirect back from main page.
if(!Auth::check) {
return Redirect::back()->with('error','Please Login');
}
i have login form, and then i try to access the controller directly, it works ! how do i prevent this access ?
i got some class
class C_home extends CI_Controller{
public function __construct() {
parent::__construct();
$this->session->set_userdata('islogin'); //to set session islogin
}
function index()
{
if ($this->session->userdata('islogin') != TRUE)
{
redirect('c_home','refresh'); //caused infinite refresh
}
redirect('c_login', 'refresh');
}
}
then i try to direct access controller, the page show infinite refresh, i want the page to show the login form
how do i resolve this ?
A couple of comments:
On the $this->session->set_userdata('islogin'); line, you should pass a 2nd argument which is the value to be assigned (presumably, TRUE is what you meant to put)
I think your redirect lines are the wrong way around. If the user isn't logged in, then you want to redirect to login. Now what your code does is redirect to home if the user isn't logged in, hence the endless loop (since this code is in the home page!
The $this->session->set_userdata('islogin', TRUE); line should obviously be in your login controller, but I'm guessing you've put it here just for testing purposes?
I'd rather do this like so
class C_home extends CI_Controller {
public function __construct()
{
parent::__construct();
}
function index()
{
if ($this->session->userdata('islogin') != TRUE)
{
redirect('c_home/login','refresh'); // go for login
}
// do something for loged in users here
}
function login()
{
if ($this->session->userdata('islogin') == TRUE)
{
redirect('c_home','refresh'); // get back home
}
// perform some login logic here
// then, if successful
{
$this->session->set_userdata('islogin',TRUE);
redirect('c_home','refresh'); // get back home
}
// or else
// display login form here
}
Of course is always better to use third party login library like this one https://github.com/DaBourz/SimpleLoginSecure
You're supposed to access the controller, that is the point of them to control things. If you have specific functions you don't want accessed via URL then prefix the function name with an _ like _notForPublicFunction. As to the infinite refresh...
if(!$this->session->userdata('isLogin'))
{
redirect('c_login');
} else {
redirect('c_home');
}
What you need to do is set up a base controller that will look after the session for you and split your logged in controllers from your logged out ones via inheritance.
It is a common question on here how best to manage logged-in and logged-out states. Please refer to this answer for detailed explanation on how to do it.
I am using native PHP sessions ($_SESSION) with CodeIgniter framework.
I have a "Login" controller loads view where user enters login and password.
After the user submits the login form, the "Login" controllers authenticate() method is called.
If everything is alright i add some data to $_SESSION array, then i redirect user to "Organisation" controllers myOrganisation() method.
I'm calling session_start() in Login/login() , Login/authenticate() and Organisation/myOrganisation() methods, but still the session is not passed, because in myOrganisation() method the session is new.
I tested my cookies functionality with creating 2 test php pages, where i just echo session id. It works perfectly.
Maybe i am not putting session_start() in all places it needs to be? (i put them in all controllers methods).
Login Controller:
class Login extends CI_Controller {
public function index() {
session_start();
$this->load->view("Login/index", $data);
public function authenticate() {
session_start();
$_SESSION['login'] = $login; // everything is alright, redirect
header("location: ".base_url()."Organisations/MyOrganisation");
Organisation controller:
public function MyOrganisation() {
session_start(); // here session is a new one, not passed
if(isset($_SESSION['login'])) {
I don't know what was wrong with the session_start() placements that i did, but the one thing that solved the problem was to place it in index.php in main folder
session_start() can also be specified in a constructor, not every method in a class. That means both your controllers can have this:
function __construct () {
ini_set("session.gc_maxlifetime", 14400);
ini_set("session.cookie_domain", .yourdomain.com);
session_set_cookie_params(14400, '/', .yourdomain.com);
session_start();
}
The first 3 lines in a constructor are to make sure the session cookie is valid for a long time and under you domain.
Besides that (and not closed index() and authenticate() methods), where's $login coming from?
I have some problems using Code Igniter and I feel there is something I don't understand because I can't get my redirects and my headers to work. Here is the situation :
When site is entered, the default "home" controller is called.
public function initialize()
{
printf("CONSTRUCTION OF HOME CONTROLLER - \n");
// print_r($_SESSION);
//TODO : CONSIDER CREATING A LIBRARY TO AVOID WRITING THIS OFTEN. NOT
// SESSION TROLLING DETECTION
if( isset($_SESSION['banana']))
{
echo "SPLITTING THE TRUTH";
}
// GETTING AS SERIOUS AS GREG
if( !isset($_SESSION['username']))
{
printf("USERNAME IS NOT SET. SETTING UP THE LOGIN PAGE. \n");
redirect('home_invite');
}
else
{
$this->load->view('welcome_message');
}
}
public function index()
{
//INITIALIZING THE PATH USED FOR THIS NAVIGATION
printf("TROLLING THE BEGINNING OF THIS CONTROLLER HOME - ");
$this->initialize();
printf("TROLLING THE END OF THIS CONTROLLER HOME - ");
//TODO : CONSIDER CREATING A LIBRARY TO AVOID WRITING THIS OFTEN
}
Index calls initialize who verify if the user has already a session variable with username in it. If that's the case, we would proceed to check his level of privileges, etc, and load corresponding view. Thats not the problem.
If the session is not started, I want to load the "login" view, called here "home_invite". And I want to redirect him to that page. But if I use this code, the page will show a 404 error.
If I use $this->load->view('home_invite'), it works, but I don't understand and I feel it isn't what I want it to do.
Why is redirect not working in this context?
Using the redirect() method redirects to a URL. You therefore need to pass it a full URL (as it uses the header() function which according to the RFC for HTTP1.1 requires a full URL.
This means that you can use
redirect(site_url('home_invite'));
Which will redirect your user to http://www.yoursite.com/home_invite
This means that you must have a controller called home_invite available as you can't load a view from the URL. Equally you could create a method in your existing controller and use the routes.php file to masquerade /your_controller/home_invite as /home_invite
The site_url() function is also part of the URL helper you've already included to use redirect().
If you don't want to use site_url(), you could just as well hard code the URL in like
redirect('http://www.yoursite.com/home_invite');
In CakePHP we can use $this->Auth->allow('someMethod'); to make a page viewable without having to login. How do I make some the same page is not viewable when a user is logged in? An example of this would be a register page which we want to be accessible without user logged in ... but not accessible once a user logged in.
I put $this->Auth->deny('someMethod') in isAuthorized() but it seems to me that if the method is in the allow list then isAuthorized is not called when we try to run that page.
Any input? Thank you
There are no complex rules like that built into Cake Auth. You'll have to manually check for conditions like this. It's very simple though:
// Controller
function register() {
if ($this->Auth->user()) {
$this->redirect(/* somewhere else */);
}
}
Contrary to mlevits answer, you don't need to store anything in the Session, the info is readily available from the AuthComponent itself. http://book.cakephp.org/view/387/user
There's also an example how to do it by dynamically using deny(), but that's not as clear in a simple case like this IMHO. http://book.cakephp.org/view/383/deny
Also, deny() produces an error message ("You're not authorized to access this location"), which is probably not what you want for the user experience in this case.
EDIT:
Wasn't aware that CakePHP used a different syntax.
You can then use the following to set the Session variable:
$this->Session->write('user_id', '<some_user_name>');
Then use this to redirect the user if they are logged in:
if ($this->Session->check('user_id'))
{
$this->redirect('http://google.com');
}
And then to destroy a Session use:
$this->Session->destroy()
More information about CakePHP Sessions
Thanks
You can check it in method beforeFilter in AppController to allow aplication-wide check. For example:
<?php
class AppContoller extends Controller {
var $components = array('Session', 'Auth');
function beforeFilter(){
$this->Auth->allow('register', 'home');
// Check if current action allowed to access without authorization and User has login
if(array_key_exists($this->params['action'], $this->Auth->allowedActions) && $this->Auth->user()){
$this->redirect(/* somewhere else */);
}
}
}
?>
Of course you can also implements it in some controller instead of AppController.