session is not destroyed - php

i have this file
secure.php
session_start();
if(empty($_SESSION['u_name'])) {
header("Location:emprego.php");
}
if(isset($_GET['logout'])) {
session_destroy();
header("Location:emprego.php");
}
$name = $_SESSION['u_name'];
?>
<li><?php echo "<a href='emprego.php?logout' id='D'>Logout</a>";?></li>
basically, if i do logout, i will be redirected to emprego.php. But if i click in back page button (arrow in browser), i can view the same page (secure.php).
my question is, why?
thanks

http://nl2.php.net/manual/en/function.session-destroy.php
Take a look at example 1 here. It clearly states that you have to clear $_SESSION as well.
if(isset($_GET['logout'])) {
unset($_SESSION['u_name']); //makes it non-existent (it does unset) that variable
session_destroy();
header("Location:emprego.php");
}

Your browser keeps a copy of the page in cache. When you click the back button, you are seeing the local cached copy, not the current page from the server. If your security is set up properly, you will not be able to do anything meaningful from that cached page.
It is for this reason that secure websites (bank sites, for example) tell you to log off and clear your cache (or close the browser) after you log out.

If you're using session cookies, also try expiring the session cookie explicitly, like this:
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
Also, going back in the browser only loads a cached copy of the page. If you tried interacting with the cached page to fetch a new page from the server, you shouldn't be able to proceed.

I recently found header_remove(); http://php.net/manual/en/function.header-remove.php
Caution: This function will remove all headers set by PHP, including cookies, session and the X-Powered-By headers.
Not sure whether this is the appropriate way to do it, but it's pretty effective for log out functionality.

All the other solutions didn't seem to work for me. However, this workaround did the trick. Basically, the code below keeps calling the logout until the logout finally succeeds:
if (isset($_GET["logout"])){
if (isset($_SESSION["username"])) {
unset($_SESSION["username"]);
session_destroy();
header("Location:/?logout=true");
exit;
}
header("Location:/");
exit;
}

Related

Session time outs and locking on different browsers

I have looked through a few previously answered questions, but the solutions don't seem to work for me.
So I have a simple login script that looks like the following:
login.php
// If page requires SSL, and we're not in SSL mode,
// redirect to the SSL version of the page
if($_SERVER['SERVER_PORT'] != 443) {
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit();
}
// put sha1() encrypted password here
$password = 'sha1passwordgoeshere';
session_start();
if (!isset($_SESSION['loggedIn'])) {
$_SESSION['loggedIn'] = false;
}
if (isset($_POST['password'])) {
if (sha1($_POST['password']) == $password) {
$_SESSION['loggedIn'] = true;
} else {
$logFailure = true;
}
}
if (!$_SESSION['loggedIn']):
// Load Login Page
exit();
endif;
logout.php
// If page requires SSL, and we're not in SSL mode,
// redirect to the SSL version of the page
if($_SERVER['SERVER_PORT'] != 443) {
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit();
}
// 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();
The rest of my pages include login.php at the top of the file.
All seems to work fine, most of the time. However, I have been noticing since I have moved over to a new server, and using php 5.6.14 that I have been getting timed out from time to time.
For example, right now I can login with Internet Explorer, but I can't with Firefox or Chrome. If I clear cookies, I can then login with Firefox and Internet Explorer, but not Chrome.
UPDATE
I can cause a timeout immediately by logging in successfully, logging out immediately, then logging in again. On the second login, it times out.
It is really been frustrating me, and I am not a session guru, so I don't understand why it is acting in this way, or how to fix it so that it isn't so delicate.
I am only using sessions to record the login, and not for anything else. I do use AJAX on certain pages within the site, but not often.
Basically, I never want this to time out. How would I prevent these time outs from happening?
I have fixed the issue. First, I had used a form button on the log out page to allow a user to log back in. I replaced that with a standard link.
Second, after login, the landing page had a section of code that would create error warnings on the log file with a foreach expecting an array (even though it was an array and outputted properly). Removing that section of code seems to have fixed the issue. I am not sure how this would cause problems.

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

Logout and header to page without cache

So, I have the following logout script (as taken from php.net):
<?php
session_start();
$_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"]
);
}
session_destroy();
header(...); //See Below
?>
The website has a header that echos either a login form (when not logged in) or "Welcome, User" (when logged in).
I have tried:
header("location:http://example.com");
in my logout script but the website header echos "Welcome, User" still until the page is refreshed. It is seemingly loading from cache(?).
One way I have gotten around this is changing the line to:
header("location:http://example.com?a=".uniqid());
As much as this works, it looks ugly in the address bar.
Is there a way to achieve the redirect without loading from cache or changing the address bar to remove the GET variable?
EDIT: OK, so this is strange... When I have the Chrome Dev Tools open to check the header response, it works fine. As soon as I close the Dev Tools, the problem comes back. Really need some help with this people!

session_destroy() and setcookie fail

I'm trying to logout of my page but session_destroy and setting cookies does not work. Here's my code:
$page = $_GET["page"];
if ($page == "logout") {
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
echo <<<html
<br /><br /><br /><p align="center"><b><font color="#000080">You've successfully logged out.</font></b></p>
<p align="right"><b><font size="3" color="#FF0000">Redirecting...</font></b></td>
html;
echo ("<META HTTP-EQUIV=Refresh CONTENT=\"4; URL=index.php\">");
exit ();
But its not working - the session is not destroyed and cookies remain the same. I've also tried just setting a cookie to a different value with no success. Other parts of the code create cookies, access and use them, but in the logout part I cant destroy them. Can someone tell me what's wrong here? Should cookies and sessions be set/unset/destroyed at the beginning of the page like session_start? Or is something else wrong?
setcookie() must be called before your scripts generates any output, as is affects the headers which are sent to the client before the actual response.
The code snippet you posted looks like you echo some stuff before the posted code is called (the output string does not contain an opening html tag). So make sure that your code is placed before any output is echoed, but after session_start() is called, then it should work.
You have to call session_start() before session_destroy() will work as session_destroy operates on the current session, which does not exist if you have not called session start.
Does the page have a session_start() before session_destroy()? It needs to be.
if we don't call
session_start()
at the beginning of the page, we cannot have session variables to operate on that page.

How to destroy the session cookie correctly with PHP?

I'm trying to correctly log out of an admin user. Here is my function:
function logout()
{
$_SESSION = array(); //destroy all of the session variables
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
}
Basically, once I authenticate the password, I set the session as being valid (only 1 user total). Now, when the admin hits logout, I want to destroy the current session, and also destroy the cookie, so that they can't just go back to the admin page using the stored session cookie in the browser. but my code doesn't work. i hit logout, and i can just directly navigate back to the admin page. however, if i delete my cookies, the functionality is perfect. so what's wrong with the cookie deleting function here?
If you really want to cover all bases try doing:
setcookie (session_id(), "", time() - 3600);
session_destroy();
session_write_close();
That should prevent further access to the session data for the rest of PHP execution. The browser may still show the cookie being set however the $_SESSION super will be blank
Maybe your problem is not the cookie, but the browser showing a cached version of your admin page. Could that be? If it disappears when you hit F5, it's probably that. This can be sorted by setting the right cache-control headers.
Check out this SO question on the issue of how to set caching. The question is about exactly the other way round (forcing browsers to cache) but you'll figure out what to change to turn caching off.
Just a tip for others who are having issues expiring session cookies:
PHP - why can't I get rid of this session id cookie?
Always use session_get_cookie_params() as in the answer to the question in the link above.

Categories