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.
Related
I'm about to write some code for mahara. I'm trying to store a variable in a cookie. If I do, it will disappear on the next page.
Example:
foo.php:
...
$myfoo = 'bar';
setcookie('mycookie', $myfoo)
var_dump($_COOKIE)
...
executing foo.php: all the mahara cookies & 'mycookie' is set. Like expected, everything's fine.
bar.php
...
var_dump($_COOKIE)
...
executing bar.php after foo.php: only mahara standard cookies set, but no 'mycookie'.
I can't really explain that.
Also $_SESSION does not work like intended.
My server is set up correctly, cookies generally work.
Has anyone an idea?
Edit: I see the cookies via var_dump in my foo.php. Even if I stop to set them. They are there. But not on other pages.
<?php
$myfoo = 'bar';
setcookie('mycookie', $myfoo, time() + (86400 * 30), "/"); // 86400 = 1 day
var_dump($_COOKIE);
?>
Your cookies are expiring because
Specifies when the cookie expires because if expiry time is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Change it to some value like time()+86400*30
For more details: https://www.w3schools.com/php/func_network_setcookie.asp
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, '/');
I have a code snippet in application whose domain is http://localhost/xyz/
I am creating a cookie using a snippet
$cookie_name = "AMCV_98DC73AE52E13F1E0A490D4C#!#$%&~|AdobeOrg";
$cookie_value = "kuchbhi";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
right after this I am trying to execute session_get_cookie_params()to get the domain details of the cookie created above using below code snippet
$cookieInfo = session_get_cookie_params();
echo $cookieInfo['domain'];
But still I do not get any domain name, even on printing the array of $cookieInfo, I get empty array.
Please suggest how exactly does the function session_get_cookie_params() works..
Function session_get_cookie_params() is based on a bunch of php.ini file values:
session.cookie_lifetime
session.cookie_path
session.cookie_domain
session.cookie_secure
session.cookie_httponly
You can set values in your php.ini file, or you can override those values at the start of your script with:
ini_set('session.cookie_domain', 'www.example.com');
As the name suggests and the manual explicits, this function gathers info about session cookies:
session_get_cookie_params — Get the session cookie
Gets the session cookie parameters.
[...]
Returns an array with the current session cookie information
In other works, it's a fancy wrapper to read some PHP settings in one line, rather than issuing five calls to ini_get().
I suspect you are confusing cookies and sessions and possibly think they're synonyms. They aren't: cookies are a client side storage and sessions are a server-side storage. PHP happens to allow (and encourage) the use of cookies in order to transmit the session ID that tells the server-side storage who you are, but that's all. Think of the session cookie as the magnetic card that opens your office: that doesn't make your MasterCard has anything to do with doors.
If your question is "how do I get back my cookie parameters" the answer is that you can't. Open your browser's developer tools and you'll see that the browser never sends that information:
whenever the ajax page is called, i run:
setcookie($filtersCookie, $cookieVal, time() + 86400); // 1 day
and when the page is refreshed, i use the following code to see if there were any past filters saved:
if(isset($_COOKIE[$filtersCookie])) {
but the cookie never exists after a page refresh. any ideas as to why this may happen?
setcookie is used before any browser output from the ajax call.
I dont think the browser will intercept the cookie when ajax call. You can do a work around like setting the cookie from javascript.
If your Ajax scripts resides in another directory than the calling page, then you should also use the path parameter
setcookie($filtersCookie, $cookieVal, time() + 86400, "/"); // 1 day
By default the cookie will be available from the directory the cookie is set on, using "/" will make it available to all paths.
OK, I'm stumped, and have been staring at this for hours.
I'm setting a cookie at /access/login.php with the following code:
setcookie('username', $username, time() + 604800, '/');
When I try to logout, which is located at /access/logout.php (and rewritten to /access/logout), the cookie won't seem to unset. I've tried the following:
setcookie('username', false, time()-3600, '/');
setcookie('username', '', time()-3600, '/');
setcookie('username', '', 1, '/');
I've also tried to directly hit /access/logout.php, but it's not working.
Nothing shows up in the php logs.
Any suggestions? I'm not sure if I'm missing something, or what's going on, but it's been hours of staring at this code and trying to debug.
How are you determining if it unset? Keep in mind that setcookie() won't remove it from the $_COOKIE superglobal of the current script, so if you call setcookie() to unset it and then immediatly print_r($_COOKIE);, it will still show up until you refresh the page.
Try pasting javascript:alert(document.cookie); in your browser to verify you don't have multiple cookies saved. Clear all cookies for the domain you're working on to make to sure you're starting fresh. Also ini_set(E_ALL); to make sure you're not missing any notices.
Seems to be a server issue. My last domain was pretty relaxed on PHP error handling while the new domain shows every error. I'm using both sites side by side and the old one removes the cookie as it should.
Is there perhaps a timezone issue here? Have you tried setting using something farther in the past, like time() - (3600*24)? PHP's documentation says that the internal implementation for deleting cookies uses a timestamp of one year in the past.
Also, you should be able to use just setcookie('username', false); without passing an expiration timestamp, since that argument is optional. Maybe including it is confusing PHP somehow?
How you use cookies data in your application?
If you read the cookies and check if username is not false or not '', then setting it to false or '' will be sufficient, since your application will ignore the cookies value.
You better put some security in cookies value, to prevent user change it's value. You can take a look of CodeIgniter session library, see how CI protect the cookies value using hash. Unauthorized value change will detected and the cookies will be deleted.
Also, CI do this to kill the cookies:
// Kill the cookie
setcookie(
$this->cookie_name,
addslashes(serialize(array())),
(time() - 31500000),
$this->cookie_path,
$this->cookie_domain,
0
);
You can delete cookies from javascript as well. Check here http://www.php.net/manual/en/function.setcookie.php#96599
A simple and convenient way, is to use this additional functions:
function getCookie($name) {
if (!isset($_COOKIE[$name])) return false;
if ($_COOKIE[$name]=='null') $_COOKIE[$name]=false;
return $_COOKIE[$name];
}
function removeCookie($name) {
unset($_COOKIE[$name]);
setcookie($name, "null");
}
removing a cookie is simple:
removeCookie('MyCookie');
....
echo getCookie('MyCookie');
I had a similar issue.
I found that, for whatever reason, echoing something out of logout.php made it actually delete the cookie:
echo '{}';
setcookie('username', '', time()-3600, '/');
I had the same issue; I log out (and I'm logged out), manually reload the index.php and then I'm logged in again. Then when I log out, I'm properly logged out.
The log out is a simple link (index.php?task=logout). The task removes the user from the session, and "deletes" (set value '' and set expiry in the past) the cookie, but index.php will read the user's auth token from the cookie just after this (or all) task (as with normal operations). Which will reload the user. After the page is loaded the browser will show no cookie for the auth token. So I suspect the cookie gets written after page finish loading.
My simple solution was to not read the cookie if the task was set to logout.
use sessions for authentication, don't use raw cookies
http://www.php.net/manual/en/book.session.php