I am working on a multilingual site so I tried this approach:
echo $_COOKIE["lg"];
if (!isset($_COOKIE["lg"]))
setcookie("lg", "ro");
echo $_COOKIE["lg"];
The idea is that if the client doesn't have an lg cookie (it is, therefore, the first time they've visited this site) then set a cookie lg = ro for that user.
Everything works fine except that if I enter this page for the first time, the first and second echo return nothing. Only if I refresh the page is the cookie set and then both echo print the "ro" string I am expecting.
How can I set this cookie in order to see its value from the second echo on the first visit/page load of the user? Should be without needing to refresh the page or create a redirect.
Answer
You can't according to the PHP manual:
Once the cookies have been set, they can be accessed on the next page
load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.
Work around
But you can work around it by also setting $_COOKIE when you call setcookie():
if(!isset($_COOKIE['lg'])) {
setcookie('lg', 'ro');
$_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
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.
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);.
Source
If you set a cookie with php setcookie you can see the set and the value of the cookie, as an example, with the developer tools of firefox just in time.
But you need to reload/load the same/next page if you wanna read, get or check the cookie and the value inside to work with that cookie in PHP.
With this example you can choose if you wanna reload the same page with PHP, HTML or JAVASCRIPT.
If the cookie is not accepted or cookies are disabled, a loading loop is obtained and the browser stops loading the page.
LONGVERSION WITH PHP 'header' RELOAD SAME PAGE:
<?php
$COOKIE_SET = [
'expires' => '0'
,'path' => '/'
// ,'domain' => 'DOMAIN'
,'secure' => 'true'
,'httponly' => 'true'
// ,'samesite' => 'Strict'
];
$COOKIE_NAME = "MYCOOKIE";
$COOKIE_VALUE = "STACKOVERFLOW";
if(!isset($_COOKIE[$COOKIE_NAME])){
setcookie($COOKIE_NAME, $COOKIE_VALUE, $COOKIE_SET);
// YOU NEED TO RELOAD THE PAGE ONCE
// WITH PHP, HTML, OR JAVASCRIPT
// UNCOMMENT YOUR CHOICE
// echo '<meta http-equiv="refresh" content="0;URL=/">';
// echo '<script>window.location.replace("/");</script>';
header("Location: /");
exit;
}
else{
echo ($_COOKIE[$COOKIE_NAME]);
}
?>
SHORTVERSION WITH PHP 'header' RELOAD SAME PAGE:
if(!isset($_COOKIE['MYCOOKIE'])){
setcookie('MYCOOKIE', 'STACKOVERFLOW');
header("Location: /");
exit;
}
echo ($_COOKIE['MYCOOKIE']);
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 would like that when someone goes on a link it executes my Cookie.
Here is my code
<?php
$globalpass = "Cuk#4Kk#Lx&?sFu}k]";
$one_year = time()+(60*60*24*365);
setcookie('password', sha1($globalpass), $one_year);
print_r($_COOKIE);
?>
That is it it is the only code... so how come the cookie does not work?
From the PHP Manual..
Once the cookies have been set, they can be accessed on the next page
load with the $_COOKIE
So you cannot try to print that on the very same page. It will be available on the other page
Also, see...
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.
This is taken directly from w3's website. I may not be understanding cookies correctly, but why is nothing displaying?
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
echo $_COOKIE["user"];
Your cookie will only be accessible when you refresh the page or navigate to a new one.
When your script loads, the HTML header fields for that page have already been set. The page will need to be rendered again (another HTTP transaction) before your cookie is available for use. Check PHP's documentation:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
check that your browser allows localhost / 127.x.x.x cookies or not ? if it allows then refresh the page. If you are using Google Chrome then you can see all browser cookies from here : chrome://settings/cookies navigate to localhost / 127.x.x.x to see your code has put cookies or not !
The variable $_COOKIE[] representates the state at the start of the script. That means that you have to wait on the next page request to see the variable. You could also add your variable manually to the global cookie variable $_COOKIE['user] = 'Alex Porter'; but the problem is that you are not sure that the browser really accepted the cookie.
I'm having issues with setting up cookies. The problem is that my cookies aren't even being set, I have setup a test below to see if they are being set but they are never being set. I've even checked in my browser to see if anything is being set, but nothing from my site.
I would like you to help me make my cookies set. I'm not quite sure what to do. Thank you.
Here is my code:
<?php
session_start();
setcookie("ridArray","", time()+3600);
if (isset($_COOKIE['ridArray'])) {
echo "ridArray is set.";
}
?>
<head>
</head>
<html>
<body>
<?php
if (isset($_COOKIE['ridArray'])) {
echo "ridArray is set.";
} else { echo "not set"; }
?>
</body>
</html>
Here's the problem, from the SetCookie documentation:
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.
You are setting the cookie value to empty string (""). Try:
setcookie("ridArray","not blank value", time()+3600);
The other issue is that when you set a cookie, it will not be in the request headers (accessed via $_COOKIE) until the next page load. This means when you load that page the first time, $_COOKIE['ridArray'] will NOT be set. On subsequent loads, it will be set, and it will be reset every time.
First page load, it won't be set. Refresh, and it will be set.
The easiest way to debug cookies is to use something like Chrome's developer tools or Firefox's FireBug and watch the response headers for the SetCookie header, and the request headers to see what cookies your browser is sending.
I am trying to setup a session management with cookies in PHP.
My code is as follows:
if(empty($_COOKIE )) {
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
I will then check session_id for 0 and print an error message if cookies are disabled.
This works fine if cookies are really disabled.
The problem is, if a user clears his history the first time he visits
the site he will get the error message even if cookies are enabled.
Anyone have any clues about this ?
Thank you in advance
When you do the setcookie call, the cookies will be sent when the header is output to the browser. This means the cookie won't be available until the next page load (when the client sends the cookie back to the server). This is mentioned in the php manual for setcookie http://php.net/manual/en/function.setcookie.php:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.
You won't be able to determine if cookies are enabled/disabled until the page has reloaded (from php). I think you'll have to do this check with javascript, or to stay in php do a redirect after setting the cookie for the first time, something like:
if(empty($_COOKIE)) {
if (isset($_GET['cookieset'])) {
// do error message, cookie should be set
}
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
header('location: http://mysite.com/index.php?cookieset=1');
exit;
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
#bencoder : I have done the test on iPad and Chrome/PC : you are right for iPad, you do need to refresh the page before you can read the cookie data, but on Chrome/PC, after deleting all cookies, if you set a new one from PHP, you can perfectly get the values directly on the first page load. Why ? There must be a more precise explanation. Why two different behaviors? Does the order of this output/availability of the data depend on the browser request to the server? Interesting to know...