Cookie set but disappears [duplicate] - php

This question already has answers here:
Why are my cookies not setting?
(10 answers)
Closed 7 years ago.
Since a few weeks, I notice that my website doesn't save cookie anymore.
If I refresh a few times this page:
<?php
print_r($_COOKIE);
setcookie('Test', 'Blah', time() + 3600 * 24 * 365, '/');
print_r($_COOKIE);
?>
cookies should be there! But I get:
Array ( ) Array ( )
Is there a common way to debug this?
Note: it's not a duplicate from this question, its answers didn't solve the problem.

$_COOKIE contains the cookies that the browser sent in the current request.
setcookie puts an instruction in the response that tells the browser to store a cookie.
The browser won't send that cookie back to the server until the next request.
If you want to test if a cookie is set you can:
Look at the response headers in your browser's developer tools
Add some JavaScript to the response body that will examine document.cookie
Make a new HTTP request and use server side code to see if it includes the cookie

Set where you want the cookie to be accessible,
setcookie('Test', 'Blah', time() + 3600 * 24 * 365 * 10, "/");
/ means that it is available everywhere on the domain.
Path
The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
Try refresh the page as it doesn't show until next request.
Reading Material
setcookie

try not to save it for 10 years . 1 year is already enough i belive
setcookie('Test', 'Blah', time() + 3600 * 24 * 365, "/");

Related

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.

session_get_cookie_params() doesn't work

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:

Unable to read cookie in php on localhost

PHP not reading cookie although I can see in browser.
//i set cookie in localhost/site/classes/php/user
setcookie("liu", $result[0]['user_id'], time() + 60 * 60 * 24 * 30, "/");
//trying to access it in localhost/site/index.php
$loggedInUser = $_COOKIE['liu'];
If you're running on localhost, you should explicitly set the cookie domain to false.
You could try:
setcookie("liu", $result[0]['user_id'], time() + 60 * 60 * 24 * 30, "/", false);
Have a further look here: Cookies on localhost with explicit domain
You cannot read a cookie you have set in the code above.
Cookies are sent with the headers to the browser.
PHP will be able to read the cookie only after the user navigates to the next page or you redirect him to a new page.
PHP will be able to read the cookie then because the browser will send it back via headers.
Read this: http://uk1.php.net/manual/en/function.setcookie.php
Common Pitfalls:
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);
We verify that we are not working in local, if we are in local we put the value of false in the variable $domain. If not, we pass the domain where the web is hosted.
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie( 'liu', $result[0]['user_id'], time() + 60 * 60 * 24 * 30, '/', $domain );

php $_COOKIE only gets session cookie?

print_r($_COOKIE) returns an array with only the session cookie and it's value, that is
Array ( [PHPSESSID] => 0cfbom6llfl3ho93n7bljnns14 )
However, I did set other cookies. I checked the browser and they do exist. I did the setting like this:
setcookie("cookie_name",$myvar,
time() + (20 * 365 * 24 * 60 * 60),
"/", "mydomain.com",
true, true
);
The browser shows the cookie name as cookie_name and the value as the value of $myvar so apparently there's no problem in the setting of the cookie.
Looking at both cookies side-by-side on the browser the only difference is that the session cookie's domain is mydomain.com while cookie_name's domain is .mydomain.com. Is that the problem? If so, how can I solve it?
Edit: The dot wasn't the problem.
Just check this page, Vist http://www.php.net/manual/en/reserved.variables.cookies.php
The first note points out why it dose not work, only if when the browser send a request back(such as a normal page visit)
you can use Chrome inspector to check the browser's request's http head.
And i'm sorry for my poor English
The problem was that I set seucre to true and my webhost did not provide HTTPS so the cookie couldn't be accessed even server-side. Silly me.

Categories