PHP Cookie doesn't work - php

I'm trying to access a cookie I just set in an other page on the same domain, but it doesn't work. When I'm doing echo $_COOKIE, the array is empty on the new page, but contains the cookie on the creation page.
Here is the code in /PROC/LOGIN.PROC.PHP
//Set the cookie for 1 year.
setcookie("username", $username, time()+365*24*60*60);
setcookie("password", $password, time()+365*24*60*60);
Here's the code in /INC/HEADER.INC.PHP
if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
include("pages/user.header.pages.php");
But when I'm trying to isset the cookie or only display the array in header.inc.php, the array is empty.

You need to set the path value of the cookie to the root of your domain, as per the docs:
setcookie("username", $username, time()+365*24*60*60, '/');
Otherwise, it will be set to the current working directory, which is /PROC/ for your example. So, only scripts in /PROC/ would be able to use that cookie.

Check out, your PHP setcookie definition is done before declare HEADs. If not, the cookie is not stored.
So take control of your cookies at the beginning of code, before sending headers or other HTML entities.

Related

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

Set cookie not working after deleting previous cookie

I want to set a cookie if Username is entered and also want the previous cookie to get deleted. I am able to unset the previous cookie but new cookie is not working for me. It showing blank.
if(!empty($User_Name))
{
unset($_COOKIE['username']);
setcookie('username', $User_Name, time()+31536000);
echo $_COOKIE['username']; // blank
}
Any help would be nice.
In my opinion there is no need to unset the cookie. Because, when you set the cookie it will override the existing cookie ( if it exists ) or create a new one ( if it doesn't exist )
From the PHP Docs..
Cookies will not become visible until the next loading of a page that
the cookie should be visible for. To test if a cookie was successfully
set, check for the cookie on a next loading page before the cookie
expires.
Found that if the path is empty it applies only to the current path, if you specify "/" applies to all paths.
so / did the trick.
setcookie('username', $User_Name, time() + (86400 * 7), "/");

PHP not retrieving cookies

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.

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

Cookies being created but unable to echo them

At the end of my registration script I set a cookie of 'loggedin' like so
setcookie("loggedin", $username, time()+60*60*24*30 );
And then just redirect back to the home page.
I'm trying to echo out the contents of that cookie. I can see it has been created when I go right click > page info > security > view cookies.
The name of the cookie is there, 'logged in' with contents set to as the username I register as. But when I do something like
print_r ($_COOKIE);
Nothing shows.
Doing a
var_dump($_COOKIE);
Gives
array (size=0)
empty
Why might this behavior be occurring if I can see that the cookie is indeed there when I follow the previous steps mentioned?
Usually it can be caused because you don't have the domain/path item set. Try Using:
setcookie("loggedin", $username, time()+60*60*24*30, '/', $domain);
you should store cookies BEFORE any output
because cookies are contained in http header, so if you start output of your html page and store cookies after that - nothing will be stored

Categories