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()
Related
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);
?>
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']
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.
}
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
my class.inc file:
<?php
class logout{
public function logout(){
$_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();
}
}
?>
used code for my logout:
session_start();
require($path."include/class.inc");
if(!empty($_GET['logout'])){
$object=new logout();
$object->logout();
$content='5;url='.$path.'index.php';
}
When the logout function is called, it destroys the session, but shows the warning:
Warning: session_destroy(): Trying to destroy uninitialized session in class.inc on line 9
I am unable to troubleshoot, as the session is not being destroyed by any other means before the session_destroy() of class.inc.
You have to call the function mentioned below at the top your logout function in the logout class.
session_start();
Add the above function and try it out. If you don’t start the session at the top of your file, it will throw exceptions like “headers already sent”, “can’t start the session”, etc.
This error is common when you haven't started the session beforehand
if (!isset($_SESSION))
{
session_start();
}
https://www.php.net/manual/en/function.session-status.php
if (session_status() === PHP_SESSION_ACTIVE)
session_destroy();
I encountered the session_destroy() error message when I started using session_write_close(). To determine if session_destroy() should be called or not, I had to do the following:
class Session {
public static function start() {
self::$haveSession = true;
session_start();
}
public static function finish() {
session_write_close();
self::$haveSession = false;
}
public static function clear() {
if (self::$haveSession) {
session_unset();
session_destroy();
}
}
}
In PHP >= 5.4 it should work to replace if (self::$haveSession) with if(session_status() === PHP_SESSION_ACTIVE).
You can add this code to start a session if it didn't start before
if(!session_id()) {
session_start();
}
Start your session
session_start(); and you can destroy your session
<?php
session_start();
class logout{
public function logout(){
$_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'll have to call session_start() before you call session_destroy();
Are you storing session in data in files or in a database. If you are storing it in a database, I normally just delete the record from the session table that corresponds to the session id, that way you don't have to unregister each session var and it actually deletes the whole session.