i would like to check if the user is idle for more than 5 minutes, they will be redirected to login page. i have no idea the best practices to do this. gimme solution. i code with codeigniter.
This can be done with combination of jQuery/javascript/Ajax and a Codeigniter function.
JS
<script type="text/javascript">
var currentSessionValue = 1;
// pseudo code
setTimeout(checkSession, 5000);
function checkSession() {
$.ajax({
url: "CheckSession/check_session", //Change this URL as per your settings
success: function(newVal) {
if (newVal != currentSessionValue);
currentSessionValue = newVal;
alert('Session expired.');
window.location = 'Your redirect login URL goes here.';
}
});
}
</script>
Codeigniter
class CheckSession extends Controller{
public function __construct(){
session_start();
}
public function check_session(){
//Below last_visited should be updated everytime a page is accessed.
$lastVisitTime = $this->session->userdata("last_visited");
$fiveMinutesBefore = date("YmdHi", "-5 minutes");
echo date("YmdHi", strtotime($lastVisitTime)) > $fiveMinutesBefore > 1 : 0;
}
}
Simply store the last_visited timestamp as a session variable. Next time when the user visits, check for difference in current timestamp against the one in session. If it is more than 5 minutes, sign out user.
$this->load->library('session');
$this->session->set_userdata(array(
'last_visited' => time()
));
I check session expiry by simply try to read a variable I stored on login
I placed this in My_Controller in the folder application/core, and extend all my other controller based on this.
in the class, I have this function
function _is_logged_in()
{
return !empty($this->session->userdata('user_id'));
}
in my class, in the __construct i do this
if (!$this->_is_logged_in()) {
$this->_log_out("Session Expired", base_url("login"));
}
so when i make a request, if the session has expired, it redirects to login, no need to check every 5 minutes.
Related
I am creating a directory site in codeigniter. On landing page load it prompts to select state then city. Then it redirects from www.example.com to www.example.com/location/city-name/.
Here Site is the controller name and location is the function name within it.
I have already removed controller name from the url using route.php. Code is below:
$route['location/(:any)'] = 'site/location';
But I want to remove function name location too from the url and url should be www.example.com/city-name/.
Further when category is selected after selecting the city it should be redirected to www.example.com/city-name/category-name/ but I am able to redirect to www.example.com/location/city-name/category-name/ only using following lines in route.php:
$route['location/(:any)/(:any)'] = 'site/location';
I can capture city and category name using $this->uri->segment and use the same for filter process there is absolutely no issue with it.
But main issue remains to remove the function name location.
I have searched suggested questions before posting this question but could't find any suitable solution. Can anyone help me to achieve the goal?
My site controller is below:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Site extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('file');
$this->load->model('query_model');
$this->load->library("pagination");
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
}
public function index(){
$this->load->view('website/index');
}
public function location(){
$this->load->view('website/index');
}
}
I think I am doing some mistake either in index or location function. Location Function is nothing just showing the view of index. Index view has the code to grab uri segment and filter the data accordingly.
My code which is passing state id to a jquery function:
<a onclick="get_cities(2)">Andaman & Nicobar Islands</a>
My jquery code get_cities(id) is below:
function get_cities(id){
var aj_url="<?= base_url();?>ajax_post_controller/show_cities";
jQuery.ajax({
type: "POST",
url: aj_url,
data: {id: id,},
success: function(res, status) {
if (res)
{
alert(res);
$("#loc-head").html("Select City");
$("#loc-data").html(res);
$(".modal-footer").css("display","block");
}
}
});
}
After defining below code:
$route['(:any)'] = 'site';
$route['(:any)/(:any)'] = 'site';
Alert from get_cities function returning html code of index page and Index page is displayed in opened model too.
If I comment above two lines I get the list of cities it returns the url of city
Visakhapatnam
But due to above 2 route lines commented above city url give an error of 404.
hope this will help you :
$route['location'] = 'site/index'; /* redirect to index method */
$route['location/(:any)'] = 'site/location'; /* redirect to location*/
$route['location/(:any)/(:any)'] = 'site/location/$1';
add like this
In routes.php
$route['location/(.*)'] = 'site/index';
In Controller
public function index(){
if($this->uri->segment(1) && $this->uri->segment(2)){
$this->load->view('website/category');
}elseif($this->uri->segment(1)){
$this->load->view('website/city');
}else{
$this->load->view('website/index');
}
}
I'm implementing redirect to previous page after login and logout.
So in each methods of controller I've saved session like as follow.
$this->session->set_userdata('previous_page', current_url());
And after successful login and logout, I'm calling a library method as follows.
function redirect_to_previous_url() {
$url = base_url();
if($this->_CI->session->userdata('previous_page')) {
// Get previous_url
$url = $this->_CI->session->userdata('previous_page');
$this->_CI->session->unset_userdata('previous_page');
}
return $url;
}
But Its redirecting to base_url of the site. After checking the session value Its showing not found image path but not what I've saved it before.
I'm not able to find out what is the problem behind this.
Please help me to rectify and the work would be appreciated
Try this..
function redirect_to_previous_url() {
$url = base_url();
if($this->_CI->session->userdata('previous_page')) {
// Get previous_url
$url = $this->_CI->session->userdata('previous_page');
$this->_CI->session->unset_userdata('previous_page');
return $url;
}
return $url;
}
I would ensure the session was set. Like this;
if($this->_CI->session->userdata('previous_page')) {
show_error('The session is set');
}
If you don't see the error, the session isn't set. Then you know this isn't where the problem lies.
No need to store Previous URL in session.
In core php you can get previously visited URL in following server variable
$_SERVER['HTTP_REFERER'];
Same can be achieved in CodeIgniter as
$this->load->library('user_agent');
echo $this->agent->referrer();
I have strange problem with sessions. In my small admin panel for my site there were some pages, 6 in fact. All worked nice. But in time I added one more page and when I go to that one firstly I see the content and after refreshing page or going to another one I'm thrown out from the account. Cookies are not deleted. It seems that session is destroyed but there is no any work with sessions. That is just infomartion page where some data from db is displayed.
This is code from index.php where session starts:
ini_set('session.gc_maxlifetime', 3600);
ini_set('session.cookie_lifetime', 3600);
session_start();
...
And this code from problem page 'orders.php':
$res = $administrator->getOrders();
while($order = mysql_fetch_array($res, MYSQL_ASSOC)) {
filtrate and print data from db in a table
}
Do you have any assumptions? I have not, was searching for an error for 2 days ;(
Check authorization function:
public function checkLogin() {
if(isset($_SESSION['hash']) && isset($_SESSION['id'])) {
$id = intval($_SESSION['id']);
$where = "`id`='$id'";
$cookie = DBWorking::getFieldWhere('cookie', 'users', $where);
$hash = mysql_fetch_assoc($cookie);
if($_SESSION['hash'] === $hash['cookie']) {
return true;
}
}
return false;
}
I am using the Default Controller to make the user authentication. What I am trying to do is whatever is the page the user request news/add or news/index or themes/all or maps/view, if he is not logged in, he or she will be directed to the log in page and then redirected to the page he wanted to go, not always the same page.
You can your the
CodeIgniter User Agent Library and Session Library to store and use the referring url. The user agent library is basicly accessing the $_SERVER['HTTP_REFERER'] value.
NOTE: from the php.net website:
Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
so this is not a foolproof method.
if ($this->agent->is_referral()) {
$this->session->set_userdata('prev_url', $this->agent->referrer());
}
// later, when login is successful
$prev_url = $this->session->userdata('prev_url');
if( $prev_url ) {
redirect($prev_url);
}
one way is to do it in the constructor of your controller. that way they are redirected before going to the news/add etc.
so for example you create a model called "sentry" and a "getUser()" method to check the browser cookie to see if the user is authorized. if they are not authorized have it return false. if they are authorized have it return $user so then you have it available for your other methods.
function __construct() {
parent::__construct();
$this->load->model( 'sentry' );
if ( ! $this->user = $this->sentry->_getUser() )
{ redirect( '/login/', 'refresh' ); }
}
so then for example you could have $this->user->name etc etc available to any method in the controller. And $this->user will also automatically be available in all the view files of this controller.
I do this by extending my controller and I check in constructor if person is logged in or not, if person is logged in I save to the session current URL, and redirect person to the login page (if same constructor is applied (controller one) I make exception to not save current URL to the session) after logging in I call redirect function to the session variable.
How to extend your controller is done here http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY
note that when your controller is extended you use $this->data['variable_sent_to_view'] and you can omit second parameter of $this->load->view()
here is some example code assuming you know how your login controller works
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->output->enable_profiler(FALSE);
if ($refer = $this->session->flashdata('refer')) {
$this->data['refer_page'] = $refer; // $this->data['refer_page'] is variable that you are interested in
unset($refer);
} else {
$this->data['refer_page'] = base_url(); //default refer_page
}
//check if user is NOT logged in
if (!$logged_in) {
$this->_setRefer(); //this is private function
}
// else dont care about it
}
private function _setRefer() {
$invalid_method = array('search', 'login'); // if method is 'search' or 'login' url will not save in session (it will stay same as was before)
$valid_refer = TRUE;
if (in_array($this->router->method, $invalid_method)) {
$valid_refer = FALSE;
}
if (!(count($_POST) > 0) && $valid_refer === TRUE && !$this->input->is_ajax_request()) {
$this->session->set_flashdata('refer', current_url());
} else {
$this->session->set_flashdata('refer', $this->data['refer_page']);
}
}
}
now in after succesful login redirect to $this->data['refer_page'], but note that login controller must by extended by MY_Controller.
this script also takes care about what happens if user made mistake and inserted wrong password (page will reload but "old" url stays)
I'm using AJAX in my web-app stuffs like search but if the user has been logged out, the ajax function return nothing because the redirection (from the action 'search' to the action 'login') has not been handled correctly.
Is it possible to redeclare the method 'redirect' in AppController to render the right action when a redirect hapend in an AJAX call ?
Thank you,
Sébastien
I think your best bet would be to setup you ajax to call to respond correctly to an invalid response. As it seems to be an important part of your app I would pass a 'loggedin' variable with every ajax request, so the client can tell as soon as the user has been logged out.
Update
In the case you want to keep a user logged in, you simply have to put the logged in/cookie check in something like your AppController::beforeFilter() that gets run with every request. for example:
public function beforeFilter() {
if($this->Auth->user() {
// USer is logged in, it's all gravy
} else {
// User is not logged in, try to log them in
$userData = $this->Cookie->read('User');
if(!empty($userData)) {
// Function that grabs info from cookie and logs in user
}
}
}
This way there will be no redirect as the user will be logged in as long as they have a cookie.
Another approach would be to allow everyone access to the Ajax function:
public function beforeFilter() {
$this->Auth->allow(array('my_ajax_method'));
}
And then check the user is authenticated in the method itself:
public function my_ajax_method() {
if (!$this->Auth->user()) {
//user not authenticated
$result = "requires auth";
}
else {
// use is authenticated
// do stuff
$result = 'result of stuff';
}
$this->set(compact('result'));
}
You will need to check the result of the ajax call in your javascript and act accordingly.