I'm just trying to set and use a cookie but I can't seem to store anything.
On login, I use:
setcookie("username", $user);
But, when I use Firefox and the Web Developer plugin Cookies -> View Cookie Information There is no username cookie.
Also, when I try to access the value from a subsequent page using
$_COOKIE["username"]
It is returning null/empty
var_dump(setcookie("username", $user));
RESULT: bool(true)
and
var_dump($_COOKIE)
RESULT: specific cookie does not exist (others are there)
I have done some more testing...
The cookie exists after login (first page) but disappears when I go to another (2nd page) and is lost for good...
Are there any headers that must be present or not present?
http://php.net/manual/en/function.setcookie.php
Try setting the $expire parameter to some point in the future. I believe it defaults to 0, which is in the distant past.
Make sure that you are setting the domain parameter correctly in case the URL is changing after you go to another page after login. You can read more about the domain parameter on http://php.net/manual/en/function.setcookie.php
The cookie is probably expired because $expire defaults to 0 seconds since the Unix epoch. (docs)
Try
setcookie("username", $user, time() + 1200);
which expires 20 minutes after set (based on the client's time).
Use var_dump() on setcookie(..) to see what is returned. Also might do the same to $_COOKIE to see if the key is set.
Thanks everyone for the feedback... Aditya lead me to further analyse the cookie and I discovered that the path was the issue...
The login path was /admin/ and then I was redirecting back to the root...
Thanks all for your help and feedback!
Related
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:
I'm using the codeigniter with xampp on a windows 7 PC.
I'm trying to use codeigniter's built in cookies, but I can't seem to get my cookies to set/stay. I know that the cookie code is going off, it's just not actually saving.
Here's the cookie code:
$this->input->set_cookie('userID', $userID, time()+259200, 'http://localhost', '/');
After running this and on every page, I've included print_r($_COOKIE); to see any/all cookies that are being set, but nothing shows up.
Is there something I've missed?
According to the docs:
The expiration is set in seconds, which will be added to the current
time. Do not include the time, but rather only the number of seconds
from now that you wish the cookie to be valid. If the expiration is
set to zero the cookie will only last as long as the browser is open.
So your code should be like this:
$this->input->set_cookie('userID', $userID, 259200);
Also i recommend you to set domain name and cookie path in the config file.
Here's the solution for anyone else that runs into this problem:
Cookies cannot be created on localhost, you'll need to use http://127.0.0.1 instead.
Go into CI's application/config/config.php and change any references to localhost you might have and change them instead to http://127.0.0.1 and do the same for the cookies. Set the following variables as well:
$config['cookie_domain'] = "127.0.0.1";
$config['cookie_path'] = "/";
Then to store the cookie: $this->input->set_cookie('userID', $userID, 259200);
I am setting a cookie containing a vlue in this format and redirecting to another page via the PHP header function. Here's the code,
setcookie("myCookie", $cookieValue, time() + $cookieLife, "/"); // cookieLife is expiration time in sec
header("Location: $baseURL/index.php"); // $baseURL is "http://localhost/mysite"
The cookie is getting set within the browser. However, I am unable to access the cookie value in the redirected page, i.e., "index.php". I am trying to access the cookie value with a simple echo like this,
echo $_COOKIE['myCookie'];
However instead of the cookie value, I get the following notice,
Notice: Undefined index: myCookie in /path/to/my/site/index.php on line 1
I have set the cookie path to "/" after looking at other solutions but am still unable to solve this.
Any help much appreciated.
EDIT :
I am testing this on XAMPP server, and the "mysite" here is actually an alias for another location on my hard drive. Could this be causing this issue?
I assume your cookie gets removed or dissapears once you've left the previous page.
Check if time() + $cookieLife is the desired time you want the cookie to live. The PHP setcookie function tells me that your $cookieLife is the time in seconds that you want your cookie to live, so make sure that it's the value you want it to be.
Use an extension to check your current cookies (and alter them if you need to). This way you can check and make sure if the cookie is living as long as you want it to (you already mentioned seeing the cookie being set, but I will include this just in case + for future visitors).
FireFox Extension: Web Developer
Chrome Extension: Cookies
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
Why when set php cookie path to "/" doesn't work for every subdirs in the domain, but just for the current directory.
cookie is set like:
setcookie("name", "val", expire_time, "/");
It just doesn't want to work.
try including the domain parameter:
setcookie("name", "val", expire_time, "/", ".domain.com");
// don't forget the prefixing period: .domain.com
that will enable all sudomains of "domain.com"
Are you testing on localhost? In that case, you need to pass null as the value for $domain.
Setting the cookie path to / should make it available to the entire domain. If you set your cookie like that, and it isn't being sent, there is something else wrong.
Try using the Web Developer addon in Firefox. It shows you details on the available cookies. Maybe that can help you diagnose the problem.
Late to the party, I know. But I just discovered that my issue was pretty stupid, but I'll post it for completion:
I was neglecting to add time() to the expires time on the cookie, so it was expiring immediately.
The expires time should be time() + seconds