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
Related
So i've tried multiple other "solutions" to my problem (both on this site and others) and cannot find a solution that works for me.
I'm trying to set a cookie to log in my user and then on log out delete that cookie. Here is my code.
list ($check, $data) = check_login($dbc, $_POST['Username'], $_POST['Password']);
if ($check) {
setcookie('Username', $data['Username'], time() + 60*60*24*90);
header('Location: RedirectPage.php');
Which, checks the username and password have been entered on the login form (and accepted), If so, the cookie "Username" is set with the username drawn from the database, and a time equalling 90 days, and the user is then redirected.
This part works fine, it logs the user in as would be expected.
However in the delete part,
header('Refresh: 0;');
setcookie('Username', '', time() - 60*60*24*90);
unset($_COOKIE['Username']);
require ('RedirectPage.php');
redirect_user();
I delete the cookie in the same way it was set, as expected, removing any data and setting the time to a negative value, and then for good measure i run the unset cookie to ensure that it has gone.
Except, this doesn't work. setcookie (to delete) does not do anything, and unset cookie only works on the page after it has been run (in this case, index.php) and as soon as i click to another page, or refresh the page it "forgets" that the cookie has been deleted.
Now going into the Chrome inspect element to check the cookie i get
Username, "Value" (the withdrawn username), r3gamers.com (domain), / (path), 2015-02-03T13:45:00 (Expires/MaxAge), 19 (Size) and HTTP and Secure are both set as empty.
Watching the process after hitting the logout button, this cookie is never deleted. The only thing which can actually delete the cookie is overwriting it with a new cookie (logging in again) or deleting it through inspect element.
Any ideas? As far as i'm aware, i'm doing everything that should be done.
EDIT:
I'd also like to mention that when testing this on localhost, offline through netbeans this functionality does work. However when i upload the pages to godaddy for my website they stop working properly.
I found the answer. It's a stupid answer too. Here is the full code file i was using for logout.
<?php
require_once ('Connection.php');
header('Refresh: 0;');
if (!isset($_COOKIE['Username'])){
header('Location: LoginFunctions.php');
} else {
setcookie('Username', '', time()-60*60*24*90, '/', '', 0, 0);
unset($_COOKIE['Username']);
header('Location: index.php');
}
?>
The problem, which i can't show here, was that the opening php tag had a single line break on it, meaning that it started on line 2. Why it was like this initially i don't know, but that small error meant that it worked on localhost and didn't work on godaddy. How frustrating. At least i've fixed the problem now.
For future use, for those stuck with the same issue, apparently godaddy (or most hosting sites) require that any cookie adding, editing or deleting occur from line 1 onwards, therefore the php tag which includes the cookie must be on line 1, no html code can preceed this php tag, or any line breaks, the php tag has to start on line 1.
You do not set the path of your cookie, I assume you want it to be site-wide, so you should set the path to '/':
setcookie('Username', $data['Username'], time() + 60*60*24*90, '/');
And then, when unsetting it, try using 1 instead of time() - 60*60*24*90 (also still specifying the path), otherwise the expiration time of the cookie might vary depending on the user's computer clock:
setcookie('Username', '', 1, '/');
I think your problem really is the path not being set: http://php.net/manual/en/function.setcookie.php
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.
The thing is, if you are in /logout/doit.php, and you try to set the cookie expiration time to a negative value, it will create a new cookie with the path '/logout/' and set its expiration time. (Instead of setting the expiration time on your site-wide cookie)
I've this little problem: PHP is not saving the cookie to my (cookie allowing) browser, other sites are fine but this one fails to save the session id in the cookie, ergo an inability to access necessary data.
The index page does a
require("includes/functions.php");
which successfully requires my functions file:
session_name('login');
// Starting the session
$expiretime = 60*60*24;
session_set_cookie_params($expiretime);
// Making the cookie live for 1 day
session_start();
However, the login cookie is not saving (checked via Firebug) and I've no reason why. Thanks for the help
Try displaying the session cookie parameters to make sure they are ok by running after session_start:
var_dump(session_get_cookie_params());
If path (or domain) doesn't match the prefix of your web app path, then you might have to set it explicitly:
session_set_cookie_params($expiretime, '/');
or
session_set_cookie_params($expiretime, '/myapp/');
This is taken directly from w3's website. I may not be understanding cookies correctly, but why is nothing displaying?
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
echo $_COOKIE["user"];
Your cookie will only be accessible when you refresh the page or navigate to a new one.
When your script loads, the HTML header fields for that page have already been set. The page will need to be rendered again (another HTTP transaction) before your cookie is available for use. Check PHP's documentation:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
check that your browser allows localhost / 127.x.x.x cookies or not ? if it allows then refresh the page. If you are using Google Chrome then you can see all browser cookies from here : chrome://settings/cookies navigate to localhost / 127.x.x.x to see your code has put cookies or not !
The variable $_COOKIE[] representates the state at the start of the script. That means that you have to wait on the next page request to see the variable. You could also add your variable manually to the global cookie variable $_COOKIE['user] = 'Alex Porter'; but the problem is that you are not sure that the browser really accepted the cookie.
Alright I'm totally baffled.
Here's my code:
if ($password == $correct_password[0] && !isset($_COOKIE['user'])) {
setcookie("user", $email, time() + 3600);
var_dump(isset($_COOKIE['user']));
echo "!";
}
So it's doing the var_dumps, meaning that the setcookie should called. But the line right after it (checking if it's set) says it's not set!
If anyone could point out the problem it'd be greatly appreciated. Thanks
$_COOKIE is populated/loaded when the script first starts up, and then is NOT updated by PHP again for the life of the script. Setting a cookie via setcookie will only show up in $_COOKIE on the NEXT execution of the script.
This applies to all of the superglobals, except $_SESSION. They're populated/initalized at script startup and then PHP does not ever touch them again. $_SESSION is populated when you call session_start() (or sessions are set to auto start), which may be done multiple times within a script's lifetime.
PHP is a server-side language.
That means that it can generate whatever it wants and will then pass it to the client.
And that's it.
There is no back and forward on a single request.
1º you instruct the page 'A' to set a cookie
2º client recieves page 'A' and sets the cookie
3º client asks for page 'B' (sending the cookie)
4º server can identify the cookie (only on page 'B')
Page here is used as simple way of understanding a server call.
You can request the same page twice for the purpose.
Still didn't find a solid valid answer, but after endless hours of testing it seems like something with the time. If I set the expiration date too close to the real time, maybe it doesn't register or something. It seemed to work when I set the time further, but I'm taking a break before heavy testing again.
Thanks
When you use setcookie() it will save its value the next time that the HTML is loaded. If you want to see the vardump with the value you just assigned you will need to use $_COOKIE['cookie_name'] = $value;
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!