Why aren't the cookies deleted? - php

I am trying to unset the cookies, I had earlier set as:
setcookie(session_name(),$sessionID,time() + 30*24*3600,'/');
setcookie('UserID',$result[0]['UserID'],time() + 30*24*3600,'/');
setcookie('UType',$result[0]['UType'],time() + 30*24*3600,'/');
setcookie('Username',$Username,time() + 30*24*3600,'/');
Logout File:
function unsetCookie() {
foreach($_COOKIE as $key => $value) {
// $_COOKIE[$key] contains the cookie name as expected
setcookie($_COOKIE[$key],'',time()-(40*24*3600),'/');
}
}
unsetCookie();
session_start();
session_destroy();
header('Location: '.$loginPage);
exit();
But after the redirect in the logout file, cookies are still not deleted. What could be the reason for this?

$_COOKIE[$key] contains the value of your cookie, not the key as that is $key.
So you would need:
setcookie($key,'',time()-(40*24*3600),'/');

Set the value to "" and the expiry date to yesterday (or any date in the past)
Try this code like that :-
setcookie("UserID", "", time()-(40*24*3600));
setcookie("UType", "", time()-(40*24*3600));
setcookie("Username", "", time()-(40*24*3600));

Related

Correct Unset Cookie method in PHP with MYSQL

I'm setting a Cookie with the following code:(admin.php)
if ($_POST['stayLoggedIn'] == '1') {
setcookie("id", $row['id'], time() + 60*60*24*365);
}
header("Location: addtip.php");
I can't get the cookie to unset, I've searched the site and the following code should be correct but it's not working;(admin.php)
if (array_key_exists("logout", $_GET)) {
unset($_SESSION);
setcookie("id", "", time()-60*60);
$_COOKIE["id"] = "";
}
Testing the cookie has been unset using the following code on the "loggedinpage" which would return to the admin login page if cookie was unset (addtip.php)
session_start();
if (array_key_exists("id", $_COOKIE)) {
$_SESSION['id'] = $_COOKIE['id'];
}
if (array_key_exists("id", $_SESSION)) {
echo "<a href='admin.php?logout' class='btn btn-danger btn-logout'>Log Out</a>";
} else {
header("Location: admin.php");
}
The problem is that you aren't clearing the $_COOKIE['id'] value correctly. You are setting it to an empty string. The idea is correct, but you have to use unset() to remove the entry from the $_COOKIE array. If you don't do that, the if() condition array_key_exists("id", $_COOKIE) will result in true even though there is no any usable value in it. And setting the $_SESSION['id'] with an empty string as well would make the following if() condition array_key_exists("id", $_SESSION) result in true as well. Therefore you get the logout link.
if (array_key_exists("logout", $_GET)) {
unset($_SESSION);
setcookie("id", "", strtotime('-1 year')); // send a header to remove the cookie
unset($_COOKIE["id"]); // remove the cookie for the remaining CURRENT http request
}
Not sure if unset($_SESSION); is the right thing to do, you might want to use session_destroy(); instead/additionally.

Detecting a cookie set using setcookie without a page reload

I am maintaining the code for an eCommerce website, they use a highly modified version of osCommerce v2.2 RC2. Was noticing an issue where the session isn't started for a new user until they visit the 2nd page of the site.
Looking at the code, before starting the session, it tries to set a cookie. If it detects the cookie it starts the session. Something along this line:
setcookie('cookie_test', 'please_accept_for_session', time()+60*60*24*30, $cookie_path, $cookie_domain);
if (isset($_COOKIE['cookie_test'])) {
session_start();
...
I found an article here that talks about a situation like this, it states:
The first time you only tell the browser to set the cookie, at the time, there is no cookie data in the request header (which could get from $_COOKIE).
Which explains why it takes two page loads for the session to be started. One to set the cookie and one to get notification from the browser that the cookie is set.
My question is, is there anyway around having to go through two page loads to detect the cookie was successfully set on the users browser?
I found this question that didn't really answer my question completely. The highest voted solution was:
setcookie('uname', $uname, time()+60*30);
$_COOKIE['uname'] = $uname;
Which may make it "work" but it doesn't truely tell me that the script was able to set a cookie successfully.
I also found this question, that suggested accessing the headers_list to find the cookie information like so:
function getcookie($name) {
$cookies = [];
$headers = headers_list();
// see http://tools.ietf.org/html/rfc6265#section-4.1.1
foreach($headers as $header) {
if (strpos($header, 'Set-Cookie: ') === 0) {
$value = str_replace('&', urlencode('&'), substr($header, 12));
parse_str(current(explode(';', $value, 1)), $pair);
$cookies = array_merge_recursive($cookies, $pair);
}
}
return $cookies[$name];
}
// [...]
setcookie('uname', $uname, time() + 60 * 30);
echo "Cookie value: " . getcookie('uname');
Which, again, doesn't seem to be verifying that the cookie was set successfully. All this appears to do is search the headers being sent to the browser for the cookie value.
The only solution I can think of is to redirect on the first visit after setting the cookie. Is there any other way?
Here is the answer:
<?php
function set_cookie($name, $value) {
if (!isset($_COOKIE[$name]) || ($_COOKIE[$name] != $value)) {
$_COOKIE[$name] = $value;
}
setcookie($name, $value, strtotime('+1 week'), '/');
}
// Usage:
set_cookie('username', 'ABC'); //Modify the value to see the change
echo $_COOKIE['username'];

Too many redirects - cookies JS + php implementation

I have a simple website where you need only a password to access the contents. Then there are 3 fields where user inputs data, which are then stored in cookies. In the end - there is a logout script that resets the session and unsets cookies.
Please find the relevant code below:
Login page (index)
<?php
session_start();
$password = '';
$wrongPassword = '';
if (isset($_POST['sub'])) {
$password = $_POST['login_passcode'];
if ($password === 'PASSCODE') {
$_SESSION['login'] = true;
header('LOCATION:/personal.php');
die();
} else {
$wrongPassword = true;
}
}
if (isset($_COOKIE['m_username'])) {
header('LOCATION:/personal.php');
die();
}
?>
The page with contents, where user inputs name, department and start date
<?PHP
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header("Location:/index.php");
die();
}
?>
and the logout script:
<?PHP
session_start();
if (isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_username'])):
setcookie('marriott_username', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_startdate'])):
setcookie('marriott_startdate', '', time() - 7000000,'/');
endif;
if (isset($_COOKIE['m_department'])):
setcookie('m_department', '', time() - 7000000,'/');
endif;
$_SESSION = array();
session_destroy();
header ("Location:/index.php");
die();
?>
jQuery to create cookies below:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Cookies do expire (at least on chrome), however after trying to access website after a few hours or days, I get the error about too many redirections. I believe this might be due to some differences between session expiration time and cookies expiration time (5 days for cookies), but I don't really know where to start fixing these...
Also, on Internet Explorer (IE8) the redirects problem occurs even when I go through logout directly.
Will be grateful for any help,
E.
You are correct in thinking different cookie expirations are behind the too many redirects problem.
If isset($_COOKIE['m_username']) is true in the index page, then you are redirected to the personal page, in which if if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) is also true, it sends you back to the index, therefore creating a loop. This would be caused by the session cookie expiring before the cookies you set.
The $_COOKIE and $_SESSION superglobals refer to two different sets of cookies. One solution is to use just the PHP session and store all your session data in the $_SESSION superglobal.
For example:
$_SESSION['m_username'] = 'whatever_value';
This will however generate an overhead in extra memory usage. If you still want to use your own cookies then just make sure any logic determining redirects is based on the session, not the presence of cookies you set.
For example:
// When logging in
$_SESSION['logged_in'] = true;
// On every page that requires login
if(!$_SESSION['logged_in']) // Redirect

How to get cookie value

Creating cookie
session_start();
$params = session_get_cookie_params();
setcookie(session_name('USERNAME'),'HAMZA',1,
isset($params['path']),
isset($params['domain']),
isset($params['secure']),
isset($params['httponly']));
session_regenerate_id(true);
echo "COOKIE IS CREATED SUCCESSFULLY !";
Now fetching cookie value
session_start();
$NAME=$_COOKIE['USERNAME'];
echo $_COOKIE["USERNAME"];
if(isset($NAME))
{
if($NAME=='USERNAME')
{
echo "success";
}
else
{
echo "error";
}
}
Please Help Me !
Result
Why they create Auto random Value Like: u8omuum6c9pkngrg4843b3q9m3).
But i want to get my Original COOKIE value Which is "HAMZA" ?????
This is the PHP syntax for cookie creation:
setcookie($name, $value, $expires, $path, $domain, $secure, $httponly);
The first variable is your cookie name, which you can use to read the value like this:
$_COOKIE['YOUR COOKIE NAME'];
Note: Like other headers, cookies must be sent before any output from your script. This requires that you place calls to this function prior to any output, including <html> and any whitespace.
Also note that dots and spaces (./ ) in cookie names are replaced with underscores (_).
Documentation: setcookie(), $_COOKIE[]
Function session_name will give you hash which atucally is you session identifier.
It seems like you want to get USERNAME stored in session, don't you? In that case you should use $_SESSION array.
Code example:
setcookie($_SESSION['USERNAME'],'HAMZA',1,
isset($params['path']),
isset($params['domain']),
isset($params['secure']),
isset($params['httponly']));
And you can get it like this:
$myCookie = $_COOKIE[$_SESSION['USERNAME']];
But from your second code it's not quite clear what you want to get.
If you want to ask for $_COOKIE['USERNAME'] and get 'HAMZA' then you should set it like this:
setcookie('USERNAME','HAMZA',1,
isset($params['path']),
isset($params['domain']),
isset($params['secure']),
isset($params['httponly']));
And when you retrieve it $NAME=='USERNAME' makes no sense, because it will be like $NAME=='HAMZA':
$NAME=$_COOKIE['USERNAME'];
echo $_COOKIE['USERNAME'];
if(isset($NAME))
{
if($NAME=='HAMZA')
{
echo "success";
}
else
{
echo "error";
}
}
try this one ...
setcookie($cookie_name, $cookie_value, 1800, "/");
change expires time with:
setcookie($cookie_name, $cookie_value, time()+ 1800, "/");
and get
$_COOKIE[$cookie_name];
try this one ...
<?
$yummy = json_decode(json_encode($_COOKIE));
if(isset($yummy->yourvar)) echo $yummy->yourvar;
?>
Why using encode and decode ?, it use to convert type Array to JSON
originally type $_COOKIE is Array

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

Categories