setcookie not setting for the following code - php

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

Related

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, "/");

Why can't I set a cookie in PHP which can be used in an If statement on the next page?

I'm trying to create a cookie within PHP.
By using the following code :
<?php
//Writing Cookie Data
setcookie("Enabled", "True", time()+3600);
setcookie("Username", $username);
//Test if cookie is set. / Just for test purposes.
echo $_COOKIE["Username"];
?>
After the cookie is set I've used a code to let users go to the next page by pressing an image (link).
This one :
<img src="image.png"></img>
And I've used a code on the next page which will check if the cookie exists.
This one :
<!-- Security Start -->
<?php
If (isset($_COOKIE["Enabled"])) {
}
else
{
header("Location: ../");
}
?>
<!-- Security Stop -->
And when the user goes to the next page he'll just be redirected to the folder specified if the security cookie doesn't exist.
I've probably setup everything correctly, and I've already checked many things, but I can't come up with a solution to this problem. The cookie should exist, and exsists.
Because the echo code works on the same page.
But after going to the next page; the cookie is suddenly gone, it doesn't exist.
Echo and using it in an If statement on the next page are both not possible.
Any ideas what might cause this?
Cookies
Some things I would do to debug this if you want cookies:
I would check the path as stated by Patrick
I would look at the return value of setcookie and see if it tells you it failed.
In your browser you should be able to see a list of all cookies, and you can check and see if the cookie was actually set. Again, look at the path here.
Using a session instead
However, I agree with the session recommendation by developerwjk, one way to do it is to make sure you call 'ob_start()' as one of the first things that happens on the page, it will then buffer the output and give you time to manipulate $_SESSION. Make sure you then call ob_flush(), to flush the buffer once you are finished with all session stuff.. I believe otherwise it will automatically flush the buffer at the end of the page but it might just discard everything..
You do not see the cookie because you have not set the PATH argument for setcookie
Using a path of "/" will enable the use of the cookie anywhere on the domain, otherwise the cookie can only be seen by scripts in the folder and sub folders of the executing script.
setcookie("Enabled", "True", time()+3600, "/");
setcookie("Username", $username,time()+3600,"/");
But as with the comments do not use cookies in place of sessions, as cookies can be easily faked.
If you already have session started you do not need to do session_start() again, if you have php 5.4 or higher you can check session status with session_status
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
or if it is lower than 5.4
if (!isset($_SESSION)) { session_start(); }
As per the user submitted comment on the session_status page

Using $_SESSION between pages that are in different directories

I was wondering how I would pass something using a session between pages that are in two separate directories. For example, if I had the following code, what would I need to add to make it work?
Page 1: directory\directory1\directory2\Page1.php
session_start();
$_SESSION['example'] = '123';
Page 2: directory\dir1\dir2\Page2.php
session_start();
echo $_SESSION['example'];
Your code should work if these pages are served within the same domain.
You do not have to session_start() in each page. Just write that, in a single file and share that file between the pages you want to hold the session in.
So, if you have page1.php and page2.php and session.php You can create session either in page1.php and check it in page two like: echo var_dump($_SESSION) and vise-versa
First of all, check if session-cookies are properly set. Some problems (e.g. Headers already sent) may cause your session cookie to not be set.
If this is working properly, you may have to change the session cookie parameters via session_set_cookie_params
By setting the second parameter (path) to /, the session cookie is valid for the root of your website and all subdirectories.
Example
session_set_cookie_params(0, '/');
The same settings can also be set in your php.ini or via ini_set(). See Session configuration
Note:
I'm not sure if these settings have any effect if session.autostart is enabled, in which case the cookie-header may already be sent before the changes are made.

Set cookie in different folders

I'm trying to create cookie from one folder that will also work in another.
Simply doing:
setcookie('favorite['.$id.']',1,time()+60*24*60*60,'/');
But it doesn't work. Cookies are visible in the created folder but empty in other.
Also I've tried:
setcookie('favorite['.$id.']',1,time()+60*24*60*60,ROOT);
setcookie('favorite['.$id.']',1,time()+60*24*60*60,HTTP_ADR);
Where ROOT = dirname(__FILE__) and HTTP_ADR is address of my site in http://example.com/site
Could it be due to problem of this array favorite['.$id.'] ?
UPDATE: using in this way echo count($_COOKIE['favorite'])
In case its not working you can store that cookie in the session and can use that cookie
<?php
session_start();
if(isset($_COOKIE['cookiename']))
{
$_SESSION['cookie_name']= $_COOKIE['cookiename'];
}
echo $_SESSION['cookie_name'];
?>
Strange.
This script which in /cookie/ foolder
<?
setcookie('foo[lol]', 1, time()+60*24*60*60, "/");
sets cookie which works even in root folder.
So make shure nothing deletes your cookies in another folder.
EDIT: php can't read cookies which contain brackets. But browsers can.
EDIT2: no, it can, but it thinks that it is array. So to read your cookie use this code:
var_dump($_COOKIE['favorite'][$id]);

Categories