Session Timeout in codeigniter dyanamicly - php

I have issue regarding codeigniter Timeout .
I know the config folder setting session timeout manually like as l
$config['sess_expiration'] = 123;
but i need to the website admin manage the session time out dyanamicly in to the admin page
please help me how to implement this logic
i tried this logic but not working
$this->session->sess_expiration = "120";
Note:here i am storing database in the value. based on the database value i can set in to the session expiration time
note 1: $config['sess_time_to_update'] = 30; this value less than of session expiration time
Total Logic code:
public function edit($id)
{
Assets::add_css('../plugins/forms/uniform/uniform.default.css');
Assets::add_css('../plugins/forms/select/select2.css');
Assets::add_css('../plugins/forms/validate/validate.css');
Assets::add_css('../plugins/misc/qtip/jquery.qtip.css');
Assets::add_js('../plugins/charts/sparkline/jquery.sparkline.min.js');
Assets::add_js('../plugins/forms/uniform/jquery.uniform.min.js');
Assets::add_js('../plugins/forms/select/select2.min.js');
Assets::add_js('../plugins/forms/validate/jquery.validate.min.js');
Assets::add_js('../plugins/forms/wizard/jquery.bbq.js');
Assets::add_js('../plugins/forms/wizard/jquery.form.js');
Assets::add_js('../plugins/forms/wizard/jquery.form.wizard.js');
Assets::add_module_js('setting','setting');
if ($_POST)
{
$current_date = date("Y-m-d H:i:s");
$data = array(
's_meta_value' => $this->input->post('s_meta_value'),
'updated_on' => $current_date
);
$this->setting_model->session_mng_update($data,$id);
$session_val= $this->input->post('s_meta_value');
if($session_val == 0)
{
$this->session->sess_expiration = '0';
}
else
{
$this->session->sess_expiration = "120";
// $val1 = $this->config->item('sess_expiration');
// print_r($val1);
//$session_seconds = ($session_val*60);
$val2 = $this->config->set_item('sess_expiration',50);
$this->session->CI_Session();
//$val1= $this->config->set_item('sess_expiration',50);
$val3 = $this->config->item('sess_expiration');
print_r($val3);exit;
}
Template::redirect('setting/setting/display');
}
$val3 = $this->config->item('sess_expiration');
print_r($val3);exit;
$data = $this->setting_model->session_mng_edit($id);
Template::set('page_title', 'Edit Session Management');
Template::set('data', $data);
Template::set_view('setting/session_management/edit_session_management');
Template::render();
}

First of all you could set cookies for this process via $this->input->set_cookie(). But if you want to overwrite the config variable then try
$this->config->set_item('sess_expiration',120);
Also call the session constructor to update the value by
$this->session->CI_Session();

You should use something like this:
$remember_me = $this->input->post('remember_me');
if ($remember_me == 'remember_me')
{
//set session to non-expiring
$this->session->sess_expiration = '32140800'; //~ one year
$this->session->sess_expire_on_close = 'false';
#$this->session->set_userdata($session_data);
}
else
{
//set session expire time, after that user should login again
$this->session->sess_expiration = '1800'; //30 Minutes
$this->session->sess_expire_on_close = 'true';
#$this->session->set_userdata($session_data);
}
//set session and go to Dashboard or Admin Page
$this->session->set_userdata(array(
'id' => $result[0]['id'],
'username' => $result[0]['username']
));

Related

Symfony 2.7.3 cookie issue

I am quite new to Symfony, and I want to set up a website were an user can select different board to display. All the board are in my twig template and are hidden if the value of the cookie is 0. If the user click on the menu, the value of the cookie will change to 1, displaying the board.
However, when I click on the menu, the first time, it does not change anything, but the second time, it work perfectly.
This is how I set up my cookie:
$var = 0;
$response = new Response();
$response->headers->setCookie(new Cookie('stream', $var, time() + 3600));
$response->send();
And this is how I change the value of the cookie:
$response = new Response();
$cookie = $this->getRequest()->cookies->get('stream');
$var = 1;
$response->headers->setCookie(new Cookie('stream', $var, time() + 3600));
return $response;
Edit: Here is my controller
public function streamAction()
{
$advert = $this->getAdvertEntity();
$stream = $this->getStreamEntity();
$cookie = $this->getRequest()->cookies->get('stream');
if (!isset($cookie) || $cookie == 0) {
$var = 1;
$response->headers->setCookie(new Cookie('stream', $var, time() + 3600));
$response->sendHeaders();
return $this->redirectToRoute('stream', array(
"adverts" => $advert,
"liststream" => $stream
));
}
$content = $this->get('templating')->render('IVPlatformBundle:Advert:Advert.html.twig', array(
"adverts" => $advert,
"liststream" => $stream
));
return new Response($content);
}
I really don't know what is wrong, so any help will be nice :)
Thanks
If you first time visit the route, cookie is not set in request, you receive it in response. Solution is to make redirect to the same route if cookie changed:
$cookie = $this->getRequest()->cookies->get('stream');
if (!isset($cookie) || $cookie == 0) {
$var = 1;
$response->headers->setCookie(new Cookie('stream', $var, time() + 3600));
$response->sendHeaders();
return $this->redirectToRoute('actual_route');
}
// Do other stuff if cookie set to 1.
return $response;

Php subtract time saved in session with current time

i am using jquery countdown timer but the problem is that timer start from value set every time on page refresh . I want to get time on first time and Save in PHP Session and subtract second time from frist time and update session etc. In Simple Word i want to create php countdown timer run only 50 using php
here is my controller code
public function actionViewtimer($id) {
$session = Yii::app()->session;
$this->layout = 'countdownlayout';
if (empty($session['countdowntime'])) {
$orderTime = microtime(true); #when user first time enter timer start from 50 mins
$session->add('countdowntime', array($orderTime)); //replace this line
} else {
$time_end = microtime(true);
$orderTime = $time_end - $time_start;
unset($session['countdowntime']);//unset old session
$session->add('countdowntime', array($orderTime)); //when user enter second
}
$getMinutes = $getMinutes_from_orderTime ; #please tell me how we extact minutes and pass them to view
$session->add('timersession', array($rand));
$this->render('viewtimerpage', array(
'getMinutes' => $getMinutes
));
}
here is my jquery code
<script>
$(function() {
$('#xlarge').countdowntimer({
minutes: 50<?php echo $getMinutes; ?>,
size: "lg",
timeUp: timeisUp
});
});
function timeisUp() {
alert('Time Complete');
return false;
}
</script>
Sorry, I've not used Yii so this example will be in plain PHP.
session_start();
if(!isset($_POST['counter']) || !is_array($_POST['counter')) {
$duration = 50;
$counter = array(
'start_time' => new DateTime()->format('Y-m-d H:i:s'),
'end_time' => new DateTime()->modify("+{$duration} minute")->format('Y-m-d H:i:s'),
'duration' => $duration
);
$_SESSION['counter'] = $counter;
}
$counter = $_POST['counter'];
$now = new DateTime();
$end_time = new DateTime($counter['end_time']);
$time_left = $end_time->getTimestamp() - $now->getTimestamp();
echo "{$time_left} seconds left";
This should be simple enough to convert, and you can easily convert seconds to minutes.
Don't destroy the session variable. Just set it the first time when its empty and then plug that value always into your countdown timer.
Inside you action
$session = Yii::app()->session;
$this->layout = 'countdownlayout';
if (empty($session['countdowntime'])) {
$date = new DateTime();
$date->modify('+50 minutes'); // Add 50 minutes to current time
$session['countdowntime'] = $date->format('Y/m/d H:i:s'); // Store date in session
}
$this->render('viewtimerpage', array(
'countdowntime' => $session['countdowntime'];
));
jQuery Code
$(function() {
$('#xlarge').countdowntimer({
dateAndTime : "<?php echo $countdowntime; ?>",
size: "lg",
timeUp: timeisUp
});
});
As I understand you want to show difference between 2 dates. Default value = 50 minutes(value for session if user first time opened page). If user refresh page after 10 minutes in view must show difference(40). It will be something like that:
public function actionViewtimer($id) {
$this->layout = 'countdownlayout';
/** #var CHttpSession $session */
$session = Yii::app()->session;
$minutes = 50; //default value for minutes
if (!$session->offsetExists('countdowntime')) {
$session->add('countdowntime', new DateTime()); //set value to session
} else {
$timeEnd = new DateTime();
/** #var DateTime $countDownTime */
$countDownTime = $session->get('countdowntime');
$interval = $countDownTime->diff($timeEnd);
$countMinutes = $interval->days * 24 * 60;
$countMinutes += $interval->h * 60;
$countMinutes += $interval->i;
$minutes -= $countMinutes;
$session->add('countdowntime', $timeEnd); //refresh value
}
// $session->add('timersession', array($rand)); don't know for what is it
$this->render('viewtimerpage', array(
'getMinutes' => $minutes
));
}
And js:
<script>
$(function() {
$('#xlarge').countdowntimer({
minutes: <?php echo $getMinutes; ?>, //without 50

CodeIgniter: How to send array from model to controller, then view

I have the following model:
// Session info in $session array.
$session = $query->row_array();
$userid = $session['uid'];
$uq = $this->db->query("SELECT * FROM `administration_users` WHERE id = $userid");
$now = strtotime(date("m/d/Y h:i:s A"));
if($session['terminatedate'] > $now) {
// If Session is STILL ACTIVE, let's give them an additional hour. Have fun!
$newterm = $now + 3600;
$userq = $uq->row_array();
$username = $userq['username'];
$userfull = $userq['name_first'] . " " . $userq['name_last'];
$this->ELog->authentication('INFORMATION',$username,"Session for $userfull has been extended by 3600 seconds (1 hour) due to activity in application.");
$this->db->query("UPDATE `administration_sessionkeys` SET terminatedate='$newterm' WHERE id='$session[id]'");
} elseif($session['terminatedate'] < $now) {
// If Session is OVER...
$userq = $uq->row_array();
$username = $userq['username'];
$userfull = $userq['name_first'] . " " . $userq['name_last'];
$this->ELog->authentication('INFORMATION',$username,"$userfull has been logged out automatically by AuthLogger due to session timeout. Thanks for stopping by. Goodbye!");
$this->db->query("UPDATE `administration_sessionkeys` SET `terminated`='1',`terminated_details`='Session Ended. Thanks for stopping by. Goodbye!' WHERE id='$session[id]'");
setcookie("ssmp_auth_cookie_uid", "", time() - 3600);
return false;
}
$userinfo[] = $uq->row_array();
return array($userinfo);
My controller, looks like this:
$this->load->model('Auth_model', "", TRUE);
$data = array($this->Auth_model->authcheck());
if(!$data) {
header("Location: /auth/login");
} else {
$this->load->view('tmpl/header', $data);
$this->load->view('dashboard', $data);
$this->load->view('tmpl/footer', $data);
}
My view is as such, and the problem here is that I can't access my array from the model in the view. What am I doing wrong? I've been racking my brain for 3 hours now on this. I need a break and some help.
<title>Logged into SSMP as <?=$id;?></title>
This should give me the "id" column in the array, right? No?
Please help me out here, sorry for so much code, I wasn't sure what you guys needed to see in order to help me out.
Thanks for all that are able to provide assistance with this irritating issue.
Scott
row_array() already returns an associative array, so you don't need to wrap the results in an array again
change
$userinfo[] = $uq->row_array();
return array($userinfo);
to
$userinfo = $uq->row_array();
return $userinfo;
Change the following :
$userinfo[] = $uq->row_array();
return array($userinfo);
to :
return $uq->row_array();
and :
$data = array($this->Auth_model->authcheck());
to :
$data['administration_users'] = $this->Auth_model->authcheck();
In you view file :
<title>Logged into SSMP as <?php echo $administration_users['id']; ?></title>
Tips: use redirect helper for redirection :
if(!$data) {
// header("Location: /auth/login");
// Assuming that you have url_helper already loaded,
// if not, uncomment the next line :
// $this->load->helper('url');
redirect('auth/login');

How to load a bunch of session variables to another controller function with codeigniter and insert them in database

im trying to write a code where a form will store all of its values inside session variables when the submit button is pressed and go to the next page where there is another form waiting to be filled up. when the submit button for the form in page 2 is pressed the variables will be stored in a session then the contents of the session variables/array will be inserted in the database. and i seem to be having problems
Summary:
Page 1 - User fills up form and the variables will be stored in a session array upon submit
Page 2 - user fills up another form and the variables will be stored in a session array upon submit
the session variables in page 1 and 2 will be inserted in the database
here is my code:
controller(site.php)
public function m1()
{
if(isset($_POST['m1']))
{
$suffix = $this->input->post("suffix");
$fn = $this->input->post("fn");
$mn = $this->input->post("mn");
$ln = $this->input->post("ln");
$nickname = $this->input->post("nickname");
$sex = $this->input->post("sex");
$bday = $this->input->post("bday");
$street = $this->input->post("street");
$city = $this->input->post("city");
$province = $this->input->post("province");
$region = $this->input->post("region");
$landline = $this->input->post("landline");
$cellphone = $this->input->post("cellphone");
$email = $this->input->post("email");
$edu_level = $this->input->post("edu_level");
$course = $this->input->post("course");
$school_name = $this->input->post("school_name");
$school_address = $this->input->post("school_address");
$school_province = $this->input->post("school_province");
$school_city = $this->input->post("school_city");
$school_region = $this->input->post("school_region");
$newdata = array('suffix'=>$suffix,
'fn'=>$fn,
'mn'=>$mn,
'ln'=>$ln,
'nickname'=>$nickname,
'sex'=>$sex,
'bday'=>$bday,
'street'=>$street,
'city'=>$city,
'province'=>$province,
'region'=>$region,
'landline'=>$landline,
'cellphone'=>$cellphone,
'email'=>$email,
'edu_level'=>$edu_level,
'course'=>$course,
'school_name'=>$school_name,
'school_address'=>$school_address,
'school_province'=>$school_province,
'school_city'=>$school_city,
'school_region'=>$school_region,
);
$this->session->set_userdata($newdata);
redirect(base_url() . "site/cmain/m/2");
}
}
public function m2()
{
if(isset($_POST['m2']))
{
$nature_complaint = $this->input->post("nature_complaint");
$newdata = array('nature_complaint'=>$nature_complaint);
$this->session->set_userdata($newdata);
$this->db->insert('myself', $newdata);
redirect(base_url() . "site/cmain/m/3");
}
}
the problem with my code is that the session variables for page 2(public function m2()) is the only one that gets inserted in the database.
is there a way to fix this?
thanks
In the first function (M1)
set your newdata in this way
$this->session->set_userdata('newdata', $newdata);
In second function (M2)
public function m2()
{
if(isset($_POST['m2']))
{
$nature_complaint = $this->input->post("nature_complaint");
$newdata = array();
$newdata = $this->session->userdata('newdata');
$newdata['nature_complaint'] = $nature_complaint;
$this->session->set_userdata('newdata', $newdata);
$this->db->insert('myself', $newdata);
redirect(base_url() . "site/cmain/m/3");
}
}
Your $newData variable is getting reset in your second function. you have already stored $newData array to session. after resetting values in second function session contains only data from second function. you need to add data in $newData instead resetting it.

can't set cookie correctly

Site built on Code Igniter framework. I have two links (like and dislike). When you click the link, the correspond value increases or decreases. You can see the site: http://joke.guluzade.com/jokes/view/24
What I want: That user can change this value only once. I do it by cookies. For example, if user click to "like" link the value +5 became +6. Then if you click "dislike" the value must not change. User should have only one chance to like or dislike. Now it doesn't work correctly, if you click like you are able to click dislike too, but I want only change the lie or dislike value only one time.
How I do: I check if the cookie is set, function does nothing, if not it sets cookie and changes value. But if cookie set for like, when you click dislike it doesn't see that cookie.
Here is code:
function vote ($mm, $id){ //get the parameters (like or dislike and id)
$name = $mm;
$value = (int)$id;
$time = time()+3600;
if(isset($_COOKIE[$value])){
redirect($_SERVER['HTTP_REFERER']);
} else {
SetCookie($value, $name, $time);
if($name == "like"){
$this->db->select('like');
$this->db->where('id', $id);
$query = $this->db->get('jokes');
$data = $query->row_array();
$likes = $data['like'];
$likes++;
$dd = array();
$dd['like'] = $likes;
$this->db->where('id', $id);
$this->db->update('jokes', $dd);
redirect($_SERVER['HTTP_REFERER']);
} else {
$this->db->select('dislike');
$this->db->where('id', $id);
$query = $this->db->get('jokes');
$data = $query->row_array();
$likes = $data['dislike'];
$likes--;
$dd = array();
$dd['dislike'] = $likes;
$this->db->where('id', $id);
$this->db->update('jokes', $dd);
redirect($_SERVER['HTTP_REFERER']);
}
}
}
Can anybody say, what I do wrong?
use get_cookie('some_cookie') OR get_cookie('some_cookie',TRUE); instead of $cookie[$value].
moreover set cookie for full domain using
$cookie = array(
'name' => 'The Cookie Name',
'value' => 'The Value',
'expire' => '86500',
'domain' => '.some-domain.com',
'path' => '/',
);
set_cookie($cookie);
You can find the answer from following posts.
How can I set a cookie and then redirect in PHP?
http://www.tek-tips.com/viewthread.cfm?qid=1509045

Categories