Share / delete cookie across subdomain (www) in php - php

I have a login/logout system and need the cookies to work across www.mydomain.com as well as mydomain.com. The problem I'm having is on deleting the cookies. On the login I am setting the cookies like this:
session_start();
//set session vars
setcookie('user_id', $row['user_id'], time() + (60 * 60 * 24 * 30), '/', 'domain.com');
setcookie('full_name', $row['first_name']." ".$row['last_name'], time() + (60 * 60 * 24 * 30), '/', 'domain.com');
Which works, and the cookies are saved and it works with or without the www. It allows the profile page to be viewed which has this code:
session_start();
if(!isset($_SESSION['user_id'])) {
if(isset($_COOKIE['user_id']) && isset($_COOKIE['full_name'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['full_name'] = $_COOKIE['full_name'];
}
}
if(!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
The problem is logging out:
session_start();
if(isset($_SESSION['user_id'])) {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 3600, '/', 'domain.com');
}
session_destroy();
}
setcookie('user_id', '', time() - 3600, '/', 'domain.com');
setcookie('full_name', '', time() - 3600, '/', 'domain.com');
The cookies are deleted but only for the current domain. So if I login from domain.com/login.php and logout from domain.com/logout.php, domain.com/profile.php doesnt work (good) but I will still be able to view www.domain.com/profile.php if I have visited the www. version before logging out. And vice versa I can logout from www.domain.com/logout.php and still be able to view domain.com/profile.php. Is there a way to delete all cookies across the subdomains?

Use '.domain.com' instead 'domain.com' to work with all subdomains.

The OP wrote in a comment:
Finally figured it out, the session was creating a separate cookie when the subdomain was changed. So logging out would delete one session cookie but leave the other. The solution was to name the session before starting it so it always has the same name:
$some_name = session_name("cool_session");
session_set_cookie_params(0, '/', '.domain.com'); session_start();

Related

PHP: Cookie Delete not working

I've created a cookie expire time 60 days... But now I am not able to delete cooking. I am using this function to delete cookie. When I refresh page then cookie is again there.
function delete_cookie($key_name)
{
$expire = time() - 3600;
setcookie($key_name, '', $expire, '/');
unset($_COOKIE[$key_name]);
}
try this
function delete_cookie($key_name)
{
$expire = time() - 3600;
$dimain = $_SERVER['HTTP_HOST'];
setcookie($key_name, '', $expire, '/', $domain);
}
also you don't need unset()
Edit:
assuming that $key_name is the cookie name

No method of un-setting cookies is working

I'm trying to unset/delete/expire cookies on a logout page. However, it doesn't seem to be working. My logout script reads as follows:
require_once("database.php"); // contains session_start()
$_SESSION = array();
session_destroy();
// attempts to unset cookies go here (see below)
var_dump($_SERVER['HTTP_COOKIE']);
header("Location: ./login.php");
exit();
My three attempts to remove a specific cookie login (or all of them), are as follows:
Attempt 1:
setcookie("login", "", time() -3600, "/");
Attempt 2:
$cookies = explode(";", $_SERVER['HTTP_COOKIE']);
foreach ($cookies as $cookie) {
$parts = explode("=", $cookie);
$name = trim($parts[0]);
setcookie($name, "", time() -3600);
setcookie($name, "", time() -3600, "/");
}
Attempt 3:
unset($_COOKIE);
However my var_dump() still contains the cookies!
Also, the page you're then redirected to, login.php contains the following code:
if (isset($_COOKIE['login'])) {
echo "Still set."
}
and low-and-behold, the page displays Still set.
First of all remove all cookies from any available Cookie tools or your browser's developer tool.
Always write COOKIES as '/' with respect to entire domain of site. Path play an important role when we set/unset cookies. Use
setcookie($cookie_name, "$cookie_value", time() +3600, "/") to set and setcookie($cookie_name, "$cookie_value", time() -360000, "/") to unset COOKIES.
Further read here for about COOKIES path: http://www.w3schools.com/php/func_http_setcookie.asp
Hope it helps you

PHP setting cookie time to past wont delete it

I have a problem with unsetting cookies. At the moment, i am unable to log out. Cookies itself works like a charm while validating user session.
So upon first login i am setting cookies in this way (on successful login):
$cookie_username = $username;
$cookie_password = sha1(md5($password));
$cookie_value = 'username='.$cookie_username.'&hash='.$cookie_password;
$cookie_name = 'remember_me#website';
$cookie_time = time() + 31536000;
setcookie($cookie_name, $cookie_value, $cookie_time, '/', '.website.com');
Cookies above work well and i dont have problems with reading them.
This is my logout code:
setcookie($cookie_name, '', time()-3600, '/', '.website.com');
unset($_COOKIE[$cookie_name]);
unset($_SESSION['username']); \
unset($_SESSION['loggedin']); / were setted after successful login
According to what i have read around SO this should work and delete cookies, however they dont :(
You have to be sure the cookie's name, domain, path, and even security settings are all identical to what you're attempting to delete.
If you created the cookie like this:
setcookie('name', 'value', time()+3600);
and then attempted to delete it like this:
setcookie('name', 'value', time()-3600, '/', '.website.com');
That won't work. You have to have the exact same parameters that were used when creating the cookie.
If you created the cookie in JavaScript, double-check your settings there.
As a test, try all of the following code. If it works, comment out each one-by-one, until you're only left with the one that worked:
setcookie($cookie_name, '', time()-3600);
setcookie($cookie_name, '', time()-3600, '/');
setcookie($cookie_name, '', time()-3600, '/', '.website.com');
setcookie($cookie_name, '', time()-3600, '/', '.website.com', 1);

Why won't my cookie go away? **UPDATE**

I'm setting an auth cookie like so:
$identifier = $this->createIdentifier($username);
$key = md5(uniqid(rand(), true));
$timeout = time() + 60 * 60 * 24 * 100;
setcookie('auth', "$identifier:$key", $timeout);
After logout I'm trying to invalidate it by doing this:
setcookie('auth', "", time() - 3600);
When I try to view a restricted page after logging out I'm checking to see if the cookie exists:
if (isset($_COOKIE['auth'])) {
error_log("COOKIE EXISTS: " . print_r($_COOKIE, true));
}
Here is my logout script:
if (!isset($_SESSION)) session_start();
$ref="index.php";
if (isset($_SESSION['username'])) {
unset($_SESSION['username']);
session_unset();
session_destroy();
// remove the auth cookie
setcookie('auth', "", time() - 3600);
}
header("Location: " . $ref);
exit();
I shouldn't be hitting this code but I am. After logging out I see the cookie has been removed from my browser. Any idea how it's finding it again after logging out?
UPDATE
This code get called from another class that checks user privs etc. The only files it doesn't work with are files that reference it from one directory above. For instance
Any file referencing it like this works OK:
<?php include_once('classes/check.class.php');
Any file referencing it like so DO NOT work:
<?php include_once('../classes/check.class.php');
Any thoughts what might be causing this?
After you log the user out you need to do a redirect to cause a new page load. Since cookies are sent with page requests until a new requests is made those cookies are still alive even after you "delete" them.

Cookies are not removing on Log Out

I've got a problem, user can't Log Out because the $_COOKIE's are not actually deleting. I can't find out what could be the problem.
This code is used only once at Log In:
// Log In
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
setcookie('user_id', $row['user_id'], time() + 2592000);
setcookie('username', $row['username'], time() + 2592000);
The code below is checking if cookies are set up to make users to be logged in when they relaunch their browser (the "keep me logged in" effect).
// Starting Session
session_start();
// If the session vars aren't set, try to set them with cookies
if (!isset($_SESSION['user_id'])) {
// This check always equals true because cookies are not deleting on Log Out
if (isset($_COOKIE['user_id']) && isset($_COOKIE['username'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['username'] = $_COOKIE['username'];
}
}
This code is launched only once on Log Out:
// Log Out
session_start();
if (isset($_SESSION['user_id'])) {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 2592000, '/');
}
session_destroy();
}
setcookie('user_id', '', time() - 2592000);
setcookie('username', '', time() - 2592000);
Don't use relative times for cookies. if you want to expire a cookie, then use Jan 1 1970 00:00:00. You're assuming that the user's clock is accurate and within an hour of your server's. Given how many people have their VCRs blinking 12:00, this is a bad assumptiong.
As well, why are you storing login information in a client-side cookie? The only cookie you should really be setting is the session cookie, which session_start() already does for you, then store all that information in $_SESSION only.
I think you're doing it way too complicated.
My example where it's just an admin login:
login.php
#session_start();
if (isset($_GET['login'])) {
if($_GET['name'] == $s['admin']){
if($_GET['pw'] == $s['adminpw']){
$_SESSION['isadmin'] = true;
}
}
}
logout.php
#session_start();
unset ($_SESSION['isadmin']);
use session_set_cookie_params() to set the lifetimes
I found why cookies were not removing!
To make sure your cookies will remove, set the same path on removing cookies as on setting them.
// Setting Cookie
setcookie(session_name(), '', time()-2592000, '/'); // The path here is "/"
// Removing Cookie
setcookie(session_name(), '', time()+2592000, '/'); // The path here is "/"

Categories