PHP - Cookie and Session Doesn't get Deleted Permanently - php

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

Related

adjust logout function to handle safari back button issue

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

PHP session destroy Trying to destroy uninitialized session

I've read several topics like:
Error — session_destroy() — Trying to destroy uninitialized session, Warning: session_destroy(): Trying to destroy uninitialized session, Warning: session_destroy(): Trying to destroy uninitialized session with phpCas
And none of them help me.
public function forbidden(){
if(!isset($_SESSION)){ session_start(); }
if(!isset($_SESSION['email']) || !isset($_SESSION['id'])){
$this->error_404();
}else{
if(!isset($_COOKIE['data'])){
session_destroy();
$this->error_404();
}
if($_COOKIE['data'] != sha1($_SESSION['email'])){
session_destroy();
unset($_COOKIE["data"]);
setcookie("data", false, time() - 3600, '/');
$this->error_404();
}
}
}
Warning: session_destroy() [function.session-destroy]: Trying to
destroy uninitialized session
I do receive that error on the second session_destroy();, the session is initialized so I don't get it?
Read This Answers of this question on stackoverflow
why session destroy not working
put this code in first and End of Your php File
<?php
ob_start();
?>
Your Code Here...
<?php
ob_flush();
?>
Your calling session_destroy() twice.
Or Removed All Sessions on server...
The problem is that you call session destroy twice. If $_COOKIE['data'] is not set, then $_COOKIE['data'] != sha1($_SESSION['email']) will return false as well and it will try to destroy the session again.
if(!isset($_COOKIE['data'])){
session_destroy();
$this->error_404();
}
if($_COOKIE['data'] != sha1($_SESSION['email'])){
session_destroy();
unset($_COOKIE["data"]);
setcookie("data", false, time() - 3600, '/');
$this->error_404();
}
Make the checks on in another
if($_COOKIE['data'] != sha1($_SESSION['email'])){
if(!isset($_COOKIE['data'])){
session_destroy();
$this->error_404();
}
else
{
unset($_COOKIE["data"]);
setcookie("data", false, time() - 3600, '/');
session_destroy();
$this->error_404();
}
}
If the cookie data is not valid, it may be because there is no cookie. This way, if it's not valid, it checks if it exists. If it does exist and it's not valid, it does something. If it doesn't, it does something else.
You're calling session_destroy() twice.
If your cookie isn't set, then it won't equal $_SESSION['email'] will it?
Change your code to:
public function forbidden(){
if(!isset($_SESSION)){ session_start(); }
if(!isset($_SESSION['email']) || !isset($_SESSION['id'])){
$this->error_404();
}else{
if(!isset($_COOKIE['data'])){
session_destroy();
$this->error_404();
} elseif($_COOKIE['data'] != sha1($_SESSION['email'])){
session_destroy();
unset($_COOKIE["data"]);
setcookie("data", false, time() - 3600, '/');
$this->error_404();
}
}
}

cookie unset not working properly

I am using remember option in my login page.I think I am doing right but when in logout I just amn't able to unset the cookie variable.I am using CI but for cookie I am using native cookie.What am I doint wrong?My code:
in login controller:
function index(){
if(isset($_COOKIE['remember_me'])){
redirect('index');
}elseif($this->input->post()){
$username = $this->input->post('username');
$password = $this->input->post('password');
$remember = $this->input->post('remember');
if($remember){
$time = time()+60*60*24*365;
setcookie('remember_me', $username , $time);
}
$this->session->set_userdata('user_name', $user_name);
$this->session->set_userdata('full_name', $full_name);
$this->session->set_userdata('server', $server->exchange_server);
redirect('index');
}else{
$this->load->view('login');
}
}
function logout(){
$this->session->unset_userdata('user_name');
$this->session->unset_userdata('full_name');
$this->session->unset_userdata('server');
$data['login'] = 'Logout Successfully.';
$data['class'] = 'success';
$this->session->set_flashdata($data);
/* To unset cookie i tried following different approach but to no avail*/
setcookie('remember_me');
setcookie('remember_me', '', $time()-60*60*24*365);
setcookie('remember_me', false);
unset($_COOKIE['remember_me']);
redirect('login');
}
but to no avail. I just can't unset cookie and when user who has checked remember me option trys to logout it's not happening.
Any help/suggestion is welcome.Thanks
I don't know what is the problem but I used jquery plugin for cookie delete {https://github.com/carhartl/jquery-cookie}. I included jquery.cookie.js and then on logout click I deleted the cookie set as $.removeCookie('remember_me')
with
unset($_COOKIE['some_cookie'])
you don't delete the Cookie on the browser, you unset the variabile $_COOKIE['some_cookie'].
If you want delete the browser cookie you have to set the expiration date in the past:
setcookie("some_cookie", "", time()-3600);
If it doesn't work try setting properly the cookie domain.
Create:
setcookie('some_cookie', null, time() + 3600, "/");
Delete:
setcookie('some_cookie', null, time() - 3600, "/");
I don't know what is the problem but I used jquery plugin for cookie delete {https://github.com/carhartl/jquery-cookie}. I included jquery.cookie.js and then on logout click I deleted the cookie set as $.removeCookie('remember_me') and it's working fine.Thanks for the suggestions and help.
Use this function please
delete_cookie()
And for native php cookie use
unset($_COOKIE['remember_me']);
Or use CI function as follows
setcookie('remember_me', null, -1);
That's all

Warning: session_destroy(): Trying to destroy uninitialized 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.

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

Categories