Can't update cookie - php

I'm running into a strange problem, I can't update cookies. I'm perfectly able to read it and to set it (just the first time). Then every time I try to update it (for logout or update the cookie's info) nothing happens.
Basically when I login I use this code
$cookie_time = (3600 * 24 * 30); // 30 days
$cookietime = time() + $cookie_time;
$cookie_name = 'login';
$cookie_value = 'enter';
setcookie ($cookie_name, 'id='.$selector.'&token='.$token, $cookietime);
and I can set it perfectly.
When I logout I use this code
$cookie_time = 1; // 1 days
$cookie_name = 'login';
$cookie_value = 'exit';
setcookie($cookie_name, $cookie_value, $cookie_time);
The cookie doesn't change at all. Even if I try to login again without logging out (I made this possible by code) the cookie doesn't change. Looks like it's impossible to update it... I made many attempts but I have no ideas how to solve it! Is it possible that my PHP doesn't allow to set cookies that are already set?

Be careful, $cookie_time should correspond to a timestamp relative to the 1 Jan 1970 and not only a time in ms.
see http://php.net/manual/fr/function.setcookie.php
$cookie_time should be :
$cookie_time = time() + (3600 * 24 * 30);
the time() function returns the actual timestamp and $cookie_time now represents a expire date in the future ;)

From the setcookie docs.
Like other headers, cookies must be sent before any output from your
script (this is a protocol restriction). This requires that you place
calls to this function prior to any output, including and
tags as well as any whitespace.
Are you outputting anything before trying to update the cookie

Related

PHP : Users getting logged out

I have a custom written PHP application. Build 15 years ago. Working perfectly fine until recently when users reported they are being logged out even while they are actively using the application.
We use PHP sessions to manage users. The session expiry is set to 12 hours of inactivity. I reproduced the issue of being logged out. There is no pattern. at times I was logged out after 30 mins, at times 2 hours, at times 40 mins and so on. I captured the PHP session cookie and checked that the corresponding PHP session file existed in the tmp directory on the server. The session file was there on the server even when the application got me logged out and it was not even 2 hours (expiry set for 12 hours).
If I print the $_SESSION, this issue does not appear as much. Reproduced the issue in Chrome and Firefox. I have session_start and session_destroy only in logout service.
Any leads what could be causing this?
I faced same problem a few times. Workaround: use a "remember me" cookie for auto login.
Here's a recipe:
Whenever user logins successfully run this:
// remember me for a year every login
$login_string = hash('sha512', $user_id . $_SERVER['HTTP_USER_AGENT'] . time());
Project::update_table_record('users', $user_id, ["remember_me" => $login_string]);
$cookie_name = COOKIE_REMEMBER_ME;
$cookie_value = $login_string;
setcookie($cookie_name, $cookie_value, time() + (86400 * 365), "/"); // 365 day example
Whenever user chooses to logout, give him the option:
setcookie(COOKIE_REMEMBER_ME, "", time() - 3600, "/");
Otherwise, if no session then re-login if cookie is valid.
// auto login / remember me!
if (!LiveUser::get_id()) {
if (isset($_COOKIE[COOKIE_REMEMBER_ME])) {
$user_string = $_COOKIE[COOKIE_REMEMBER_ME];
$user_id = Project::get_value('users', ['remember_me' => $user_string], 'id');
if ($user_id) {
Project::do_login($user_id);
}
}
}

Why do my cookies expire instantly?

I have a function that sets cookies; in this function I use PHP's setcookie function in order to set cookies, for example:
setcookie('auth', $token, time() + 3600);
The function I'm using setcookie in is as follows:
function SetAuthenticationCookie($id, $rememberme) {
$token = md5(uniqid(mt_rand(), true));
executeNonUserQuery([db query]);
if ($rememberme) {
setcookie('auth', $token, time() + (86400 * 90));
setcookie('profid', $id, time() + (86400 * 90));
}
else
{
setcookie('auth', $token, time() + 3600);
setcookie('profid', $id, time() + 3600);
}
}
The above cookie should be valid for one hour, and appears this way in the browser (see below screenshot).
In the browser the cookies show before it redirects (the page is dynamic), therefore the cookies are being set. However they disappear when the page redirects. This causes a problem because the main UI page (where the login page redirects) checks for the presence of the authentication cookies and redirects back to the login page if they don't exist.
I followed the official documentation for setcookie and am unable to see what the problem is. Chrome reports that the cookie path is /internal therefore it's a possibility that the actual page can't access them (the page path is /pages), but this still doesn't explain why they disappear completely from Chrome.
The cookie is set to expire in an hour after it is set, but this doesn't explain the disappearance of the cookies unless I'm missing something crucial in setcookie concerning the setting of the expiration time. I experience the same issue in other browsers, so it has to be something that I've done wrong or missed.
I confirm that I have nothing that unsets or expires the cookies (I haven't implemented that yet). I've tried setting the path to / but this doesn't fix the problem.
What am I doing wrong, and how can I fix it?
I'm aware of the security issues here, my priority is to fix this problem first.
This issue was caused by two factors:
The cookie path
PHP's timezone
As mentioned in the question I had already tried setting the cookie path to / with no effect. However I did not consider PHP's timezone, which was set to UTC.
Setting the timezone to the correct Europe/Guernsey plus setting the cookie path to / (root) fixed the issue.
Ok, add a path and make it available to the whole website rather than just the folder the first script is in
setcookie('auth', $token, time() + 3600, '/');

PHP setcookie won't work

I am completely baffled by this problem. Setting a cookie should be the easiest thing in the world, but for whatever reason it's just not working. Currently I'm just trying to get a test-script to work. It looks like this:
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + 86400 * 30, "/");
setcookie("act", "sj", time() + 86400 * 365);
setcookie("bbba", "Hello", time() + 86400);
echo $_COOKIE['act'];
echo $_COOKIE['bbba'];
echo $_COOKIE['user'];
None of these cookies will set. Nothing will echo, and I can not find the cookies when using the inspector. I've tried the following:
- Placing the echo $_COOKIE in another file in the same directory.
- With and without ob_start() and ob_flush()
- Using "/", "/direcotry" and nothing at all as path
- Moving the file to the root directory to see if it works there.
Nothing seems to work, and I cannot see what could possibly be wrong. Other scripts using cookies are working on the same domain - which is located on a web hotel.
Can anyone see the problem here?
Cookies will not become visible until the next loading of a page that
the cookie should be visible for. To test if a cookie was successfully
set, check for the cookie on a next loading page before the cookie
expires. Expire time is set via the expire parameter. A nice way to
debug the existence of cookies is by simply calling
print_r($_COOKIE);.
It's from php manual. You can set the value in $_COOKIE array by manual if you really want it in same page which's declared.
$_COOKIE['key'] = 'value';
echo $_COOKIE['key'];
PHP Manual setcookie
The problem was caused by whitespace at the beginning of the document.

php cookie not setting after logging out

I'm making a website where some users can log in. I have my code create a simple cookie. Earlier my code was working and creating a cookie and allowing users to sign in. However, after I created a log out button and used it, I couldn't seem to create a cookie again (my website doesn't recognize a cookie and no cookie shows up in chrome when I check). I've already looked at all the other threads about creating a cookie and not being able to create a cookie, but I can't figure out what is wrong.
Here is my code to create a cookie:
$userStuff = array('name' => $username,'password' => $password);
$date_of_expiry = time() + 60 * 60 * 24 * 1 ;
setcookie( "user", $userStuff, $date_of_expiry, "/" ) ;
I know that the security is extremely lax and that I shouldn't store the password and such directly in a cookie, but I want to work on other things first. This code is before any html.
Here is my code where I changed the expiration date of the cookie to log out:
setcookie('user', $userStuff, time() - 3600, '/');
how are you?
If you want to delete a cookie, you should pass a date in the past, for example:
setcookie('user', $userStaff, time() - 3600, '/');
Regards.
I know this is a bit aside the point, but why not use $_SESSION? It stores a cookie with a session token in your client's browser (when you run session_start) and most of the data is stored server side which is far more secure. For user auth data and tokens this is probably a better choice.
Example:
//First thing init the session
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//Or retreive the data...
$username = $_SESSION['username'];
//Later when you want to log out just destroy the session:
session_destroy();
I found the error. Apparently, you either cannot use arrays in cookies, or it just wouldn't let me use an array in my cookie this time.

PHP: setting cookies - the old values isn't replaced for some reason

I have a script where I set 2 cookies:
$month = time() + 60 * 60 * 24 * 30;
setcookie('id', $id, $month, '/');
setcookie('auth', $auth, $month, '/');
header('Content-Type: text/html; charset=utf-8');
print('<html><body>...etc....');
This does work well, but: some users have several id's, depending on from which page (social network) they access my script through an iframe.
A user having several id's is not a problem. But my problem is that when I ask that person to look at his cookies, he'll report that there are several cookies called id and auth. And I can reproduce it myself too.
And I was actually expecting there always to be just 1 id and 1 auth cookie.
What can I do here?
Doesn't calling setcookie('id', ...) with a new value replace the old value?
Thank you!
Alex
Cookies are based on a KV Scheme (Key=Value) concept and the Key's act as unique identifiers.
The three primary effectors of setcookie are
CREATE
Create a cookie with setcookie("id","value")
READ
Read a cookie with $_COOKIE["id"]
UPDATE
Update a cookie with setcookie("id","new value")
DELETE
Delete by setting the expiration in the past setcookie ("TestCookie", "", time() - 10);
so yes your correct in your question, you should have a look at other factors that may deter the cookie states.

Categories