Cookies only work when in a certain directory - php

I have set up a simple login page on http://mywebsite.com/control. When you login, it places a cookie called user on your computer. To set the cookie I simply use:
setcookie("user", $_POST['IGN']);
When I am on the directory /control, it works fine. For example, if I use the code:
echo $_Cookie['user'];
it echos out the cookie information. However, if I do this on any page that is not in the /control directory, it says:
Notice: Undefined index: user in /var/www/other/vars.php on line 16
Line 16 is where it echos. This is an image of the cookie information in Chrome:

You should use:
setcookie("user", $_POST['IGN'],0,'/');
if you want cookie to be visible in the whole domain
You should also use:
echo $_COOKIE['user'];
with capital letters
You should also read more about setting cookies at http://www.php.net/manual/en/function.setcookie.php - by default cookies are set only for directory where you set cookie. That's why you need to add as 4th parameter '/'

It does that because you are not setting the path parameter when you set your cookie, and by default, PHP will take the current directoy you're in.
Try this.
setcookie("cookiename", "value", time()+3600, "/", "mywebsite.com");

Related

the cookie disappear when I change page

(PHP) I set the cookie in my login.php page in this way:
setcookie('cookie_id',$id);
I print the cookie and I see the correct value but when I change page with:
header($login_url);
I lose the all cookie and I don't know why. Anybody can help me?
You have to specify / as path in setcookie() function, so cookie will be available on every path of your site. To do this:
setcookie('cookie_id', $id, 0, '/');
Note that third argument is expire time which is set to 0 as default. According to documentation it means that:
If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
If you have human urls or subfolders (like www.domain.com/path1/path2/), then you must set cookie path to / to work for all paths, not just current one.
setcookie('cookie_id', $cookie_id, time() + 60*60*24*30, '/');
From PHP manual:
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.

Php cookie won't unset/delete - can't logout

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)

PHP isset for cookie not working

I am facing some trouble with a conditional statement that uses cookies in PHP.
I would like to change the state of an image based on whether a cookie is set or not. Here is my code (in file MAIN.PHP):
$cookie = "d_content_vote_".$databaseArray['id'];
if(!isset($_COOKIE[$cookie])) {
// display image 1 if cookie is not set
}
else {
// display image 2 if cookie is set
}
The cookie value (of the timestamp) is set in ../INCLUDES/RATING.PHP, and I make an ajax call to that file. In order to debug, I did a print_r($_COOKIE) in RATING.PHP which gave me this:
Array
(
[d_content_vote_1] => 1402726678
[d_content_vote_4] => 1402727148
[PHPSESSID] => effa8778efbe1b3dfb5bb301e359997d
)
However, when I do a print_r($_COOKIE) in MAIN.PHP I do not get the d_content_vote_* cookies, only the session info.
How do I transfer the cookie that is set in rating.php so that I can use it in main.php. I have never faced this problem before.
[Additional info: I'm building the site on a MAMP server now]
I realised that my cookie was being set and the print_r was done in a file in a subdirectory (/includes) and therefore cannot be used in the root directory. In order to make it work in the root directory, I needed to add another attribute to the function:
setcookie($name, $value, $time, "/");
The last parameter "/" ensures that the cookie can be used in the root directory.
What about the cookie remove when a user make the log-out process? In case we use 4 parameters when setting the cookie, do we need to adopt the 4 parameters both in the log-out process?
setcookie($NomeCookieLogOut, "", time()-3600);
OR
setcookie($NomeCookieLogOut, "", time()-3600, "/");

setcookie not setting for the following code

set cookie is not setting the value for the following code.
<?php
session_start();
ob_start();
unset($_SESSION['adminname']);
session_destroy();
if(isset($_COOKIE['adminremember_me'])) {
$past = time() - 100;
setcookie('adminremember_me', gone, $past);
}
header("Location: login.php");
exit();
?>
Cookie is not deleting as setcookie donot works though an error message is not displayed.
Interesting part is that i have another file with same code structure but with different cookie name for normal user logout and that one works.
I moved the admin logout file which was in (htdocs/site/admin/)to (htdocs/site) and now logout works!!! seriously what change didit make?
You can have multiple cookies with the same name but different paths. So if you script is in /folder1/folder2/mypage.php, you can have 1 cookie with the path /folder1 and another with the path /folder1/folder2, and both cookies could have the same name.
My guess is the cookie you are trying to delete belongs to a different path (by default, if you don't specify a path, then it assumes the folder that the script is in). To delete it, you will have to manually set the path parameter to match that of the cookie. For example:
setcookie('adminremember_me', gone, $past, "/");
or
setcookie('adminremember_me', gone, $past, "/folder1/");
To see what the path is on the existing cookie, you need to use your browser's cookie viewer to see what path is set on it.
Edit: to answer the question in your edit, when you moved the location of your logout file, you moved it to be in the same folder as the path that was set on the cookie (so the default value was now the same). If you want to move the script back to the old location, just explicity set the path to whatever the folder was where it worked

Unable to access cookie after page redirect

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

Categories