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.
Related
When a user loads a page, I want to test whether they have gone from the login page OR have a cookie on their PC saying that they have logged in previously, however it seems the latter doesn't work.
if ($pass === $PassConfirm || $_COOKIE['loggedIn'] == "true"){
//Set cookie for logging in, (86400/24) lasts 1 hour
setcookie("loggedIn", "true", time() + (86400 / 24), "/");
/* Code to do stuff */
}else{
echo 'You are not logged in';}
This is what I am using to test they have just logged in OR have the cookie. If I enter the page from the login page, with the correct password, it loads just fine. However, when checking that the value of the cookie is "true" (which it gets set as, and I can see is set when I look at my cookies for the page in Chrome) it errors saying I am not logged in.
Your code structure needs some heavy refining, if you insist on using cookies, so be it, but it is recommended (in comments and by others) to use $_SESSION instead of cookies (as their data contents are stored more securely and use cookies to communicate with the end user in the same way).
Reform your code to now do:
if (password match){
//password check
}
elseif (cookie match){
//cookie check
}else {
//unauthorised. (You should redirect).
}
So
if (password_verify($pass, $PassConfirm)){
/***
Password is matched with the hash so now set the cookie
***/
//set cookie - I will say more about this further down...
setcookie("loggedIn", "true", time() + (86400 / 24), "/");
}
elseif ($_COOKIE['loggedIn'] == "true") {
/***
Cookie data found so assumed correct. carry on.
***/
}
else{
echo 'You are not logged in';
/***
Some form of error handling. Typcially a header() statement and page redirection
***/
header("Location: index.php");
exit;
}
// Now your "rest of code" activity can begin here safe in the
// knowledege that only people with passwords or cookies will reach this part.
Please read up about PHP Password Verify and the corresponding Password_hash functions.
Your cookie checks can and will be manipulated, make an improvement by using SESSIONS, which also handle lifetimes and logging in and out much easier as well.
for failed states such as the else statement you should ideally not stay on the same page and redirect the user to another page via an intermediary page which will clear the cookie/session data and "clean" their associated data.
Please read the notes from the manual for setcookies, including:
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. Expire time is set via the expire parameter. A nice way to
debug the existence of cookies is by simply calling
print_r($_COOKIE);.
Cookies must be deleted with the same parameters
as they were set with. If the value argument is an empty string, or
FALSE, and all other arguments match a previous call to setcookie,
then the cookie with the specified name will be deleted from the
remote client. This is internally achieved by setting value to
'deleted' and expiration time to one year in past.
Because setting a
cookie with a value of FALSE will try to delete the cookie, you should
not use boolean values. Instead, use 0 for FALSE and 1 for TRUE.
Which should be enough for you to get a clear idea on whatyou've done wrong with your cookies:
Also read:
If output exists prior to calling this function, setcookie() will fail
and return FALSE. If setcookie() successfully runs, it will return
TRUE. This does not indicate whether the user accepted the cookie.
So an associated cause is that your string cookie content value is looking like a boolean variable (due to PHP generally loose type casting), so try using a numeric equivilant boolean value 0 or 1 and that should appear correctly.
So:
if(setcookie("loggedIn", 1, time() + 3600, "/", "", false, true)){
print "Biscuit has been set!";
}
And after a page reload (note you should update your code check further up this code sample to look [more] similar to this piece here):
if($_COOKIE['loggedIn'] == true){
//cookie exists!
}
If you are still having problems then I recommend using PHP Error logging and/or print_r($_COOKIE); at the top of your PHP page.
Use Sessions. They're much easier and safer.
I'm trying to access a cookie's value (using $_COOKIE) immediately after calling the setcookie() function in PHP. When I do so, $_COOKIE[$cookiename] isn't set after login. Why?
if(isset($_SESSION)){
$_SESSION['email']=$username;
$_SESSION['id']=$query['id'];
$_SESSION['name']=$query['name'];
$_COOKIE[$cookiename]=$query['name'];
$cookiename="user";
$cookie_value = "John Doe";
setcookie($cookiename,$cookie_value, time() + (86400 * 30),"/");
if (!$session->Check()){
echo $cookiename ;
}else {
echo $_COOKIE[$cookiename];
}
This is because when you call setcookie() you are attaching the cookie to the current response(when the current request completes).
$_COOKIE will have a value when a request is made with the cookie header already set i.e cookie is sent to the server.
So, when only #1 happens you don't have anything in $_COOKIE, but once #2 happens you will have a value in $_COOKIE
EDIT: Almost everything you need is mentioned in the manual
http://php.net/manual/en/function.setcookie.php
setcookie() defines a cookie to be sent along with the rest of the
HTTP headers Once the cookies have been set, they can be accessed on
the next page load with the $_COOKIE array. Cookie values may also
exist in $_REQUEST.
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), "/");
I'm exploring the source code of Kohana framework, and it has the following logic when deleting the cookie on browser:
public static function delete($name)
{
// Remove the cookie
unset($_COOKIE[$name]);
// Nullify the cookie and make it expire
return setcookie($name, NULL, -86400, Cookie::$path, Cookie::$domain, Cookie::$secure, Cookie::$httponly);
}
I understand that the function setcookie will set cookie's name to deleted (as displayed in browser cookies view) and expire it so that the browswer doesn't send it next time. So why is the first part with unset is there?
setcookie add cookie to HTTP response headers. Whereas $_COOKIE presents cookies from request headers. So setcookie doesn't affect on cookies of $_COOKIE array (on the current page load). Therefore we have to unset cookie in $_COOKIE too in order to ensure that this cookie won't present in $_COOKIE array if we'll want to get it in further (on the current page load).
both are same and deleting cookie. If we remove unset, Surely it will work and delete the cookie.
In an attempt to get more familiar with cookies I've decided to set up a simple cookie management system to have more control of the information that I can store and retrieve from a user.
The idea is to set a cookie if it does not exist, and update a cookie if it already exists on the user.
Once the cookie is set, it will also be stored in a database that will keep track on when the session started and when it was last accessed.
Creating a cookie worked well at first. But suddenly it stopped working and wouldn't set anything at all. This is the current code of the createSession() function:
function createSession() {
// check to see if cookie exists
if(isset($_COOKIE["test"])) {
// update time
$expire = time()+81400;
setcookie("test","$cookiekey",$expire,"/",false,0);
} else {
// assign unique cookie id
list($msec,$sec)=explode(" ",microtime());
$cookiekey = preg_replace("/./","",($msec+$sec));
// set time
$expire = time()+81400;
// set cookie
setcookie("test","$cookiekey",$expire,"/",false,0);
// assign the unqiue id to $_COOKIE[]
$_COOKIE["test"]=$cookiekey;
unset($cookiekey);unset($msec);unset($sec);unset($expire);
}
}
Is my approach heading in the right direction or have I done something way wrong?
Doing $_COOKIE["test"] = something; doesn't make a "test" cookie. You need to use setcookie again.
I don't know why you'd want to do that though. Why not just check for $_COOKIE["name"] (the cookie that you are making).
Cookies are only available once another request was done. So don’t modify $_COOKIE on your own.
Furthermore, when in your case the cookie exists (i.e. $_COOKIE['test'] is set) you call setcookie again with $cookiekey as its value. But $cookiekey is not defined at that moment so the cookie will be overwritten with an empty string. I guess you want to use $_COOKIE['test'] instead:
if (isset($_COOKIE["test"])) {
// update time
$expire = time()+81400;
setcookie("test", $_COOKIE["test"], $expire, "/", false, 0);
}
You could also save yourself all that pain by using PHP's built in session management (examples here) to handle all of this cookie stuff for you.