PHP Application logs out within seconds - php

I have a PHP/MySQL application which processes a lot of data. When I use session regeneration, my application logs the user out over and over again within a matter of seconds.
To resolve this, I disabled the session regeneration. I have set gc maxlifetime = 86400.
Could it be possible that a memory leak or long execution time of some heavy PHP script/loop which is not coded properly be at the source of this problem?
function checklogin()
{
if ( isset($_SESSION['LAST_ACTIVITY']) && ( time() - $_SESSION['LAST_ACTIVITY'] > 86400 ) )
{
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
}
function login()
{
session_start();
// session_regenerate_id(); //ON USING IT LOGSOUT, SO I STOPPED USING THIS
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
}
I need to use the session regeneration but it shouldn't log out.

session_start() must be the first instruction execute ever if you want work with cookies.

Related

Php Session Variables Destroyed Without Instruction For This

I just use Session Variables in my code. I do not start any activity with cookies. I just do session_start() and do the manipulation of the variables.
But at the end of some time (about 30 minutes) the session goes down. If I do print_r ($ _ SESSION) the session is in void.
I've tried set session.gc_maxlifetime to 7200 (2 hours), but the session is destroyed in less than 30 minutes again.
How can I resolve this? It's normal? Should the session not only be destroyed if I close the browser or give the statement/instruction to session_destroy?
The default timeout is 24 minutes.
Other than php.ini, you can change it in code. You could try this:
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 3600);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(3600);
session_start(); // ready to go!
from this answer: How to change the session timeout in PHP?
An article on it:
https://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
which gives code that I've adapted to 2 hours.
session_start();
$timeout = 7200; // Number of seconds until it times out.
// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
// See if the number of seconds since the last
// visit is larger than the timeout period.
$duration = time() - (int)$_SESSION['timeout'];
if($duration > $timeout) {
// Destroy the session and restart it.
session_destroy();
session_start();
}
}
// Update the timout field with the current time.
$_SESSION['timeout'] = time();
php.net page on it:
http://php.net/manual/en/function.session-set-cookie-params.php
Other stack answers verify this (some highly rated):
PHP sessions default timeout
How do I expire a PHP session after 30 minutes?
Session variables are meant to hold information until the browser is closed. I am not quite sure what you want to achieve in your project, since you have not posted any code.
Something simple like not putting session_write_close(); at the end of your php script or session_start() at the very beginning, before any html tags could be messing your code.

PHP - Session destroy after closing browser

Though this question has multiple duplicates i could not find proper solution for me.
Need Some help.
I have used ini_set('session.cookie_lifetime', 0); in my configuration file.
But it is not helping me to destroy session on browser close.
Application current flow:
1) In authentication page if user is valid, generate new session identifier using session_regenerate_id(true);
2) Control goes to welcome.php where i start new session using session_start();
3) in logout page code is
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
This might help you,
session_set_cookie_params(0);
session_start();
Your session cookie will be destroyed... so your session will be good until the browser is open. please view http://www.php.net//manual/en/function.session-set-cookie-params.php this may help you.
Use a keep alive.
On login:
session_start();
$_SESSION['last_action'] = time();
An ajax call every few (eg 20) seconds:
windows.setInterval(keepAliveCall, 20000);
Server side keepalive.php:
session_start();
$_SESSION['last_action'] = time();
On every other action:
session_start();
if ($_SESSION['last_action'] < time() - 30 /* be a little tolerant here */) {
// destroy the session and quit
}
The best way is to close the session is: if there is no response for that session after particular interval of time. then close. Please see this post and I hope it will resolve the issue. "How to change the session timeout in PHP?"
There are different ways to do this, but the server can't detect when de browser gets closed so destroying it then is hard.
timeout session.
Either create a new session with the current time or add a time variable to the current session. and then check it when you start up or perform an action to see if the session has to be removed.
session_start();
$_SESSION["timeout"] = time();
//if 100 seconds have passed since creating session delete it.
if(time() - $_SESSION["timeout"] > 100){
unset($_SESSION["timeout"];
}
ajax
Make javascript perform an ajax call that will delete the session, with onbeforeunload() a javascript function that calls a final action when the user leaves the page. For some reason this doesnt always work though.
delete it on startup.
If you always want the user to see the login page on startup after the page has been closed you can just delete the session on startup.
<? php
session_start();
unset($_SESSION["session"]);
and there probably are some more.
There's one more "hack" by using HTTP Referer (we asume that browser window was closed current referer's domain name and curent page's domain name do not match):
session_start();
$_SESSION['somevariable'] = 'somevalue';
if(parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST) != $_SERVER["SERVER_NAME"]){
session_destroy();
}
This also has some drawbacks, but it helped me few times.
You can do it using JavaScript by triggering an ajax request to server to destroy the session on onbeforeunload event fired when we closes the browse tab or window or browser.
Use the following code to destroy the session:
<?php
session_start();
unset($_SESSION['sessionvariable']);
header("Location:index.php");
?>
If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.
<?php
session_start();
session_regenerate_id(true);
?>
If you close your browser your session is lost.
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser.
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up.
ini_set('session.cookie_lifetime', 176400); // for 48 hours
ini_set('session.gc_maxlifetime', 176400); // for 48 hours
session_start();
If you are confused what to do, just refer to the manual of session_destroy() function:
http://php.net/manual/en/function.session-destroy.php
There you can find some more features of session_destroy().

Disconnect a user after 5mins

Can somebody please help me on how to disconnect a user (using sessions) after 5mins regardless of being idle or active.thank you
am coding in php and mysql as the database.
When the user logs on, you could register a session variable for the time, every time a page is loaded, check if 5 minutes has elapsed since logging on.
For example:
<?php
session_start();
if($_SESSION["loggedin"] && ($_SESSION["timer"]<(time()-(5*60)))) {
logout();
}
function login() {
//do login stuff
$_SESSION["timer"]=time();
}
function logout() {
//do logout stuff
}
?>
Use session.gc-maxlifetime:
ini_set('session.gc-maxlifetime', 60*5);
Once above line is read by the php interpreter, your session will expire after 5 minutes.
You can save a timestamp of the last action in the $_SESSION array and compare $timestamp + 300 with the current time.
Just setting the garbage collector lifetime to a low value won't work because the garbace collector doesn't run on every page request.

how to destroy the session if the application is exceeding more than its given idel time using php

in my program for a security purpose it is neccessary to destroy the session variable if the application exceed more than its idle time.For This i am using this code,
// set timeout period in seconds
$inactive = 300;
// check to see if
$_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() -
$_SESSION['start']; if($session_life
$inactive)
{ session_destroy(); header("Location: logout.php"); } }
$_SESSION['timeout'] = time();
But this code refresh the session variable every 5 min, i want to know how to destroy the session variable if the system is in the idle time. And also please tell me it create any other problem if i destroy the session variable . Thanks in advance
session_unset
#Edit:
Since the session data are considered garbage after the session timed out, no action should be needed really. It should be sufficient, to make sure, the garbage is cleared in a regular manner. So simply calling a page which creates a dummy session (once a minute fe.) should be enough. The garbage collector frequency may also be configured in php.ini.
However, you can verify this easily by monitoring your sessions (in file / database / memory).
Try this:
Edit php.ini - set session.cookie_lifetime with the intended value in seconds (300 seconds for your 5 minutes).
Restart your apache server.
Login
Test the session variable after 5 minutes (should have expired).
Remember, from the docs:
The default "0" value means that the cookie stays alive until the browser is closed. This is also the default value, if not set in php.ini.
So, you must set it: it defaults to zero - so it will never expire unless someone closes the browser window.

PHP session_id() not accepting existing session id

I'm having trouble forcing sessions to restart in PHP. Here's the problem:
I can get my session id with session_id(), copy it, and add to the very top of my script:
session_id('the_session_id');
session_start();
And when I open a new browser, the session from the other browser is not carried over. What settings can I check?
Reason:
If you close the browser window and open it again, then at this moment a second session is started with a different ID, if the used web application has some session based authentication system the user has to login again. At the same time the user has to logout twice!
Solution:
This function will use a real cookie for the session ID and updates the expiration time with every script execution. The expiration is equal to the PHP directive "gc_maxlifetime" (default) or every custom value. So, put this function in your PHP file. We will need it.
<?php
// $expire = the time in seconds until a session have to expire
function start_session($expire = 0)
{
if ($expire == 0)
$expire = ini_get("session.gc_maxlifetime");
else
ini_set("session.gc_maxlifetime", $expire);
if (empty($_COOKIE['PHPSESSID']))
{
session_set_cookie_params($expire);
session_start();
}
else
{
session_start();
setcookie("PHPSESSID", session_id(), time() + $expire);
}
}
?>
Now, in the top of your page where you're issuing session_id('the_session_id'); and session_start();, remove those lines and start session with this code below:
To start a session with an expire time given by the php configuration
start_session();
To start a session that will expire in 1 hour:
start_session(3600);

Categories