PHP - Session destroy after closing browser - php

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().

Related

User authorization php/mysql with session [duplicate]

I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?
session_start();
if(isset($_SESSION['foo'])) {
unset($_SESSION['foo'];
...
}
session_destroy();
In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?
To destroy a session you should take the following steps:
delete the session data
invalidate the session ID
To do this, I’d use this:
session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();
And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:
session_start();
if (!isset($_SESSION['CREATED'])) {
// invalidate old session data and ID
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:
if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
The PHP Manual addresses this question.
You need to kill the session and also remove the session cookie (if you are using cookies).
See this page (especially the first example):
http://us2.php.net/manual/en/function.session-destroy.php
In the one site I've made where I did use PHP sessions, I never actually destroy the session.
The problem is that you pretty much have to call session_start() to check for your $_SESSION variables, at which point, lo and behold, you've created another session anyway.
Hence on my site I just made sure that every page called session_start(), and then just unset() those parts of the session state that matter when the user logs off.
$_SESSION = [];
#unset($_COOKIE[session_name()]);
session_destroy();

After payment success session destroying automatically

I am doing a small project in that i have user data in session. In the middle the user will do payment, after payment success, the session is destroying automatically.
Now am not able to get user data from session. (How can i achieve this with out using COOKIES).
Note: I have tried using:
header('Access-Control-Allow-Origin: *');
But no use.
Hello this is an example from PHP manual i hope it might help. Firstly start your session by session_start(); and once all your transactions are completed destroy is by session_destroy();
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
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();
?>
$_SESSION is a special array used to store information across the page requests a user makes during his visit to your website or web application.
While there may be many users accessing the site at the same time, each with his own session, it’s thanks to unique IDs assigned and managed by PHP for each session that allows each user’s session to be available only to himself. Session information is stored on the server rather than the user’s computer (as cookie data is stored), which makes sessions more secure than traditional cookies for passing information between page requests.
Using Sessions
Before you can to store information in a session, you have to start PHP’s session handling. This is done at the beginning of your PHP code, and must be done before any text, HTML, or JavaScript is sent to the browser. To start the session, you call the session_start() function in your first file:
<?php
// start the session
session_start();
// store session data
$_SESSION["username"] = "Qateel";
session_start() starts the session between the user and the server, and allows values stored in $_SESSION to be accessible in other scripts later on.
In your second file, you call session_start() again which this time continues the session, and you can then retrieve values from $_SESSION.
<?php
// continue the session
session_start();
// retrieve session data
echo "Username = " . $_SESSION["username"];
Ending a Session
As important as it is to begin a session, so it is to end one. Even though a session is only a temporary way to store data, it is very important to clean up after yourself to ensure maximum security when dealing with potentially sensitive information. It is also good practice and will avoid having a huge amount of stale session data sitting on the server.
To delete a single session value, you use the unset() function:
<?php
session_start();
// delete the username value
unset($_SESSION["username"]);
To unset all of the session’s values, you can use the session_unset() function:
<?php
session_start();
// delete all session values
session_unset();
Both examples only affect data stored in the session, not the session itself. You can still store other values to $_SESSION after calling them if you so choose. If you wish to completely stop using the session, for example a user logs out, you use the session_destroy() function.
<?php
session_start();
// terminate the session
session_destroy();
Few Tips
Despite there simplicity, there are still ways using sessions can go wrong.
Timing-out sessions is a very important action if you are dealing with users logged in to your website or application.
if (isset($_SESSION["timeout"])) {
// calculate the session's "time to live"
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_destroy();
header("Location: /logout.php");
}
}
Use a database to store data at the earliest moment you know the data will be persistent; don’t let it stay as part of the session for too long as this opens it up to possible attack.
Use session_destory() once you don’t need to use the session any more.
You may want to go through:
php sessions at #SO
php sessions security at #SO

Clear session on browser exit for php

I am working on a PHP project where in I need to clear the seesion on click browser close.
My project :
Index.php -> userdata.php -> reports.php ->finalreport.html
is it possible to handle session destroy?
I need to clear session , whenever user exits browser while they are in any page.
Please let me know how can we handle this.
the session is destroyed when the user closes the browser**. if you want to destroy it as soon as the user unloads the page, you could add a handler to the page unload event (something like jquery unload) and do a ajax request to a script that just clears the session.
EDIT: per OP's request, i'll add specific code.
1) in all pages (Index.php, userdata.php, reports.php, finalreport.html) add this javascript code
$(window).unload(function() {
$.get('session_destroyer.php');
});
2) in session_destroyer.php use this code (taken from php.net)
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
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();
?>
hope this helps
** NOTE: as one commenter noted, this assumes you're using cookie-based sessions (which is the default in PHP, i think)

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

Truly destroying a PHP Session?

I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?
session_start();
if(isset($_SESSION['foo'])) {
unset($_SESSION['foo'];
...
}
session_destroy();
In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?
To destroy a session you should take the following steps:
delete the session data
invalidate the session ID
To do this, I’d use this:
session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();
And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:
session_start();
if (!isset($_SESSION['CREATED'])) {
// invalidate old session data and ID
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:
if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
The PHP Manual addresses this question.
You need to kill the session and also remove the session cookie (if you are using cookies).
See this page (especially the first example):
http://us2.php.net/manual/en/function.session-destroy.php
In the one site I've made where I did use PHP sessions, I never actually destroy the session.
The problem is that you pretty much have to call session_start() to check for your $_SESSION variables, at which point, lo and behold, you've created another session anyway.
Hence on my site I just made sure that every page called session_start(), and then just unset() those parts of the session state that matter when the user logs off.
$_SESSION = [];
#unset($_COOKIE[session_name()]);
session_destroy();

Categories