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, "/");
Related
(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.
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)
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
This PHP code is supposed to write to a file in a folder specified by a cookie:
$user = $_COOKIE["username"];
if( $xml = file_get_contents("$user/docs.xml") ) {
But it just says the file /docs.xml (not specifying the folder) just the file and not the cookie value, apparently doesn't exist, because it's not getting the cookie but why?
Could it be that I'm trying to get it from a different domain?
Try setting the cookie like so
setcookie("Name", "Value", $time, "/");
The / at the end make sure the cookie works throughout the whole site, not just the folder where it was set.
i'm using codeigniter and i have all the routes like this
www.example.com/path1/
www.example.com/path1/path_/
In every page i do a control if SESSION['lang'] is set.
if it's set I also set the Cookie
setcookie("lang", $_SESSION["LANG"], time() + (60* 60 * 24 * 30 *12 *20), "./");
But i have a problem...
when I do Logout from admin area I must delete the session and also the cookie.
But if i Delete a cookie in this way
setcookie("lang",'', time() - (60* 60 * 24 * 30 *12 *20), "./");
it will delete only one cookie lang.
I must delete all cookie "lang" of different path.
Someone can help me?!
To set a global cookie for the entire site the path should be "/" without the dot.
"/" means the root of the website.
"./" means current directory.
In your case to set the global cookie it should be:
setcookie("lang", $_SESSION["LANG"], time() + (60* 60 * 24 * 30 *12 *20), "/");
To delete the global cookie:
setcookie("lang",'', 1, "/");
Regarding your actual question, "Delete all cookie with same name and different path" there is no official documented way to do it. There is a hack using the $_SERVER['HTTP_COOKIE'] variable like here.
But this variable is not documented and could be non existent on some servers.
The way which you use to set a cookie stores a separate cookie for each page/URL that you visit because:
setcookie(..., ..., ..., "./"); // the 4th parameter means "this directory"
So if the script get executed on every page then every directory and subdirectory that you visit will get a separate cookie. However, this is not necessary if you want to set the "lang" parameter for a whole part of the domain.
If you change it to something like "/foo/" then this cookie will be valid for any http://www.example.com/foo/ and any subdirectory of www.example.com/foo/, see http://php.net/manual/en/function.setcookie.php:
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.
Because this will store only one cookie for the whole part of the domain, you can easily invalidate it using your code with the 4th parameter changed:
setcookie(..., ..., ..., "/foo/");
I hope this helps.
Codeigniter has a method to delete cookies
delete_cookie()
Lets you delete a cookie. Unless you've set a custom path or other values, only the name of the cookie is needed:
delete_cookie("name");
This function is otherwise identical to set_cookie(), except that it does not have the value and expiration parameters. You can submit an array of values in the first parameter or you can set discrete parameters.
delete_cookie($name, $domain, $path, $prefix)
With this function you can delete the cookie of any path or domain. Perhaps you need to write this function so many times as "domain/path" you have
http://ellislab.com/codeigniter/user-guide/helpers/cookie_helper.html