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), "/");
Related
I'm making a website where some users can log in. I have my code create a simple cookie. Earlier my code was working and creating a cookie and allowing users to sign in. However, after I created a log out button and used it, I couldn't seem to create a cookie again (my website doesn't recognize a cookie and no cookie shows up in chrome when I check). I've already looked at all the other threads about creating a cookie and not being able to create a cookie, but I can't figure out what is wrong.
Here is my code to create a cookie:
$userStuff = array('name' => $username,'password' => $password);
$date_of_expiry = time() + 60 * 60 * 24 * 1 ;
setcookie( "user", $userStuff, $date_of_expiry, "/" ) ;
I know that the security is extremely lax and that I shouldn't store the password and such directly in a cookie, but I want to work on other things first. This code is before any html.
Here is my code where I changed the expiration date of the cookie to log out:
setcookie('user', $userStuff, time() - 3600, '/');
how are you?
If you want to delete a cookie, you should pass a date in the past, for example:
setcookie('user', $userStaff, time() - 3600, '/');
Regards.
I know this is a bit aside the point, but why not use $_SESSION? It stores a cookie with a session token in your client's browser (when you run session_start) and most of the data is stored server side which is far more secure. For user auth data and tokens this is probably a better choice.
Example:
//First thing init the session
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
//Or retreive the data...
$username = $_SESSION['username'];
//Later when you want to log out just destroy the session:
session_destroy();
I found the error. Apparently, you either cannot use arrays in cookies, or it just wouldn't let me use an array in my cookie this time.
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.
In a file I have this code to set some cookies
setcookie("token", "value", time()+60*60*24*100, "/");
setcookie("secret", "value", time()+60*60*24*100, "/");
setcookie("key", "value", time()+60*60*24*100, "/");
I want to know how I can check if these cookies were set on the same file, preferably just after they're set. I have tried this
if(!isset($_COOKIE['token']) || !isset($_COOKIE['secret']) || !isset($_COOKIE['key']){
//do something
}
but it doesn't work..
the $_COOKIE is set when the user already have a cookie and ask for a new page.
You can't setcookie then use $_COOKIE right after
We shouldn't really bother with your question as you didn't take any advice from your previous question about the exact same problem, but here goes:
Option A
// As you do setCookie, also set the value in $_COOKIE
setCookie("foobar", "bat", time() + COOKIE_LIFETIME);
$_COOKIE["foobar"] = "bat";
var_dump($_COOKIE["foobar"]);
Option B
Don't use $_COOKIE to store your information. Have separated variables $token, $secret and $key and load these with the values from $_COOKIE. If $_COOKIE is empty, initialize them manually and call setCookie.
if (isset($_COOKIE["token"]))
$token = $_COOKIE["token"];
else
{
$token = "defaultValue";
setCookie("token", $token, COOKIE_LIFETIME);
}
// Use $token instead of $_COOKIE["token"] from now on.
Option C
If the user does not have the cookies set, do setCookie and relocate the user to the same site again with header(). Beware of infinite relocates if the user does not allow you to set cookies.
if (!isset($_COOKIE["token"])
{
setCookie("token", "defaultValue", COOKIE_LIFETIME);
header("Location: ".$_SERVER["REQUEST_URI"]); // insert reasonable URL here.
exit;
}
Option B would be the preferred one. Hope to not see this question asked a third time.
You can't check in the same request if the user will send your cookies in future requests. setCookie is merely an appeal to the users browser to please attach this information to future requests. You will know if it works, if the cookie is send on the next request. If it does not following 3 scenarios are possible: a) The user's browser does not allow you to set cookies, b) the user has not visited your website before, c) previously set cookies have expired.
I have a page (mypage.html) which sets a cookie as follows:
setcookie ("sessionid", md5 (uniqid (rand())));
Now, at the top of an include which displays the site header I have the following:
echo "cookie is ". $_COOKIE['sessionid'];
When I am on mypage.html, which includes the header, the echo command displays the cookie name, as it should...e.g.
cookie is 4d40102ff2d2268d907dd31debc411e2 cookie is 4d40102ff2d2268d907dd31debc411e2
But if I move aeway from the page which set the cookie, all I see is
cookie is
with no name - If I go back to mypage.html it reads it again with no problem. I have no clue how this can happen?? Any ideas?
Set an explicit path for the cookie. The default is the current directory only, so if you navigate to a script in another directory, the cookie won't be sent back by the browser.
// Cookie is valid for all paths ( / ) in the current domain
// This also has an explicit expiry time of 1 hour from the time it's set...
setcookie ("sessionid", md5 (uniqid (rand())), time() + 3600, "/");
It's a little unusual to be setting your own session cookies though, when simply initiating a session handles it for you:
session_start();
// Id is set for you...
echo session_id();
What I'm wanting to do is for the remember me checkbox. I have it set up to where if there is a cookie set for the username then it checks the checkbox. What I'm wanting to do is if there was a cookie but the user decides to uncheck it just in case someone else wants to access their account from the same computer then it'll delete the cookie I"m not sure how to accomplish this. Here's what I have so far.
if (isset($_POST['remember'])) {
// Sets an expiration time for the cookie
$my_expiration = time()+60*60*24*100;
// Sets the cookie for the username
setcookie("username", $username, $my_exiration, "/");
} else {
setcookie ("username", "", time() - 3600);
}
This will work if you add the path ("/") to the second setcookie() call. Since you are omitting that, the browser is treating the cookie as a different one than the previously-set cookie, and will therefore not delete it:
setcookie ("username", "", time() - 3600, "/");
(At least I assume that's what's going wrong. You didn't actually ask a question, you just sort of threw code up there and said "I'm doing this" without indicating if anything isn't working as you expect.)
Set it to null
setcookie("username", null, 0, "/");
Both setting and deleting must have path
setcookie("ST",$_COOKIE['ST'],time()+1000,'/'); //for creation
setcookie('ST',NULL,-1,'/'); //for deletion
I played with this until get it done.
Hope it useful.