adjust logout function to handle safari back button issue - php

I have the following logout() function that works on most browsers but not safari. The problem in safari is after logout if the user hits the back button they get the previous page from cache instead of the login screen. Is there a way to adjust the logout function to handle this?
function logout()
{
// unset any session variables
$_SESSION = [];
// expire cookie
if (!empty($_COOKIE[session_name()]))
{
// setcookie(session_name(), "", time() - 42000);
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]);
}
// destroy session
session_destroy();
}

It seems to me it is a browser issue more than a server issue.
Have you tried configuring caching headers in order to disallow caching of logged pages ?
As an other solution, I found a SO post in relation: Preventing cache on back-button in Safari 5 .
You could try this solution which is basically putting this javascript in your logged pages:
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload() ;
}
};
To only reload the page after a logout you could check there is no cookie, such that the back button still work when logged in for instance. Just change the "yourCookieName" string to your session cookie name.
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return null;
}
function hasCookie(cname) {
return getCookie(cname) !== null;
}
window.onpageshow = function(event) {
if (event.persisted && !hasCookie("yourCookieName")) {
window.location.reload(); // or redirect to login page
}
};
Note: I think the cache will still exists in Safari with solution 2. So, this is not really a solution handling correctly security in my opinion.

Use redirect function in your code like
function logout()
{
// unset any session variables
$_SESSION = [];
// expire cookie
if (!empty($_COOKIE[session_name()]))
{
// setcookie(session_name(), "", time() - 42000);
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]);
}
// to redirect the user to login page
$return_url = "login.php"; //I'm using login.php you can change it according to your page
// destroy session
session_unset();
session_destroy();
header('Location:'.$return_url); //to redirect to user
}
And also use to verify the user session is exist or not by
session_start();
if($_SESSION[name]=="") {
header("location:index.php");
}
Note: Need to be in all page to authenticate the user to access the
page if only having the session

Related

PHP - Cookie and Session Doesn't get Deleted Permanently

I trigger the function below in all my web pages.
function refresh_user_auth() {
if (isset($_COOKIE["UserID"])) {
$_SESSION["UserIDS"] = $_COOKIE["UserID"];
setcookie("UserID", $_COOKIE["UserID"], time() + (86400 * 30), "/");
}
elseif (isset($_SESSION["UserIDS"])) {
$_SESSION["UserIDS"] = $_SESSION["UserIDS"];
setcookie("UserID", $_SESSION["UserIDS"], time() + (86400 * 30), "/");
}
}
I use the function below to log out but it doesn't seem to have logged me out when I visit other web pages on the website.
function unset_user_auth() {
if (isset($_COOKIE["UserID"])) {
unset($_COOKIE['UserID']);
$_COOKIE = array();
setcookie('UserID', '', time() - 36000);
}
if (isset($_SESSION["UserIDS"])) {
unset($_SESSION['UserIDS']);
$_SESSION = array();
session_destroy();
setcookie('UserIDS', '', time() - 36000);
}
}
Please, what am I doing wrong?
I'm not sure why you have to do that separately for cookie and session, you can do that all at once. When logging out, it isn't required to check if cookies are set and/or session is set if you're going to destroy both anyway (unless you have an option to save cookie for 'Remember me' function).
Here's an example from a comment in the PHP documentation for session_unset() function page. You could always refer to PHP documentation when in doubt. You'll find ample examples and use cases in the comments.
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
?>

Trouble in destroying session

I am having trouble in destroying session when user logout of its account. After logging out when i browse any page which is restricted to user not to access before login i can access that but if i close my browser after logging out and then try to access the page i cant. Please solve my problem so that user cannot access the pages after logging out even he/she has not closed the browser. Here's my code of logging out and destroying session.
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
if(isset($_POST['logout'])){
session_start();
// Unset all of the session variables.
$_SESSION = array();
$_SESSION["Alogin"] = "";
// 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 session_start() must be at the top
<?php
// Initialize the session.
session_start();
// If you are using session_name("something"), don't forget it now!
if(isset($_POST['logout'])){
//What ever you want
// Finally, destroy the session.
unset( $_SESSION );
session_destroy();
//redirect to loginpage
header('Location:../login.php');
exit;
}
?>
Put your session_start (); outside the if statement and
check with print_r ($_POST); if you send $_POST['logout']

Can you help me debug my session time out function?

Hi I am creating secure login functionality for my site. I have a function called sessionTimeOut() which i call at the top of each page of my site. As you can see within the function, if the user has been inactive for more than 30 mintues, I call a logOut() function and also a secure_session_start() function before redirecting the user back to the login page. I'm wondering will these functions execute fully before the redirect occurs? I'm not sure of the best way to debug the code. any help would be appreciated thanks.
function sessionTimeOut(){
//We implement a session timeout of our own. We use a simple time stamp that denotes the time of the last activity (i.e. request)
//and update it with every request
if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
//last request was more than 30 minutes ago
logOut();
//start a new secure session so that we can create a new session variable.
secure_session_start();
//create a session variable to say that the login session has timed out after redirecting to the login page.
$_SESSION['loginTimedOut'] = true;
header('Location: login.php');
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); //update last activity time stamp
//Now we also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions
if(!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
}else if(time() - $_SESSION['CREATED'] > 1800) {
//session started more than 30 minutes ago
session_regenerate_id(true); //change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); //update creation time
}
}
logout() function:
function logOut(){
//Unset all session values
$_SESSION = array();
//get session parameters
$params = session_get_cookie_params();
// Delete the actual cookie.
setcookie(session_name(),
'', time() - 42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]);
// Destroy session
session_destroy();
}
function secure_session_start() {
/* This is a function to start a PHP session in a secure way.
* This function stops crackers accessing the session id cookie through JavaScript (for example in an XSS attack).
* Also the session_regenerate_id() function, which regenerates the session id on every page reload, helps prevent session hijacking
*/
$session_name = 'secure_session_id'; // Set a custom session name
$secure = false; //set to true if https
//This stops JavaScript being able to access the session id.
$httponly = true;
//Forces sessions to only use cookies.
if(ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
//Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
//Sets the session name to the one set above.
session_name($session_name);
session_start(); //Start the PHP session
session_regenerate_id(true); //regenerate the session, delete the old one to prevent session fixation attacks.
}

cookie didn't destroy straight away, cookie disappear after 1 minute

I have set up if no session OR cookie, the page will header to index. The session destroy works fine, however cookie has the problem.
When I destroy cookie(log out), the page didn't head to index straight away, have to wait for 1 min. The cookie is gone after 1 minute. Anyone know where is the problem.
setcookie('id', $id, time()+60, "/");
function destroySession() {
$_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();
}
You're setting a cookie with the name id and trying to unset a cookie which name is the result of session_name(). That will work if session_name() happens to return id but not if it returns something else.
I would use session_name() to set the cookie:
$id = session_id();
setcookie(session_name(), $id, time()+60, "/");
Also note that it's probably best to use the session_set_cookie_params() for all parameters. The cookie is set automatically when you call session_start()

why does my php session information behave differently on a different server

I'm writing a simple web site php/jquery/mysql etc. Currently I've a pretty simple login system where once the user logs in a session variable is set that is referenced to confirm if they're still logged in on other pages. Code is:
$_SESSION['logged_in'] = TRUE;
$_SESSION['member_id'] = $member_id_for_session;
$_SESSION['handle'] = $user_handle;
I have a variety of functions in util files that make use of this such as:
function echoUserHandle() {
if (isset($_SESSION['handle'])) {
echo "Welcome " . $_SESSION['handle'];
} else {
echo "You are not logged in";
}
}
and
function checkLoggedIn() {
if (isset($_SESSION['logged_in'])) {
return TRUE;
} else {
return FALSE;
}
}
this works fine on my MAMP server on my mac using chrome however when I push it out to my remote server I get inconsistent views of the data even on the same browser I use to dev on. I see this only by the fact that some pages show the status "You are not logged in" whilst some display the correct user id.
Also once a user is logged out the session is destroyed fully using:
unset($_SESSION['logged_in']);
unset($_SESSION['member_id']);
unset($_SESSION['handle']);
$_SESSION = array();
if (ini_get("session.use_cookies")) {
error_log("unsetting cookie:" . session_name(), 0);
$params = session_get_cookie_params();
error_log("cookie params:" . $params, 0);
setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
}
session_destroy();
this might be overkill but, when I log back in as a different user on some pages it still displays the previous logged in user. This suggests something wrong with the session doesn't it?
Can anyone suggest an approach to debug this, I've done a lot of dev in other fields but php is still new to me.
Many thanks

Categories