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
Related
I have created two session and want to check the username cookie is created and check first_login =='True' in if condition.
I have created cookie as
setcookie($userName, '1', time()+(24 *3600));
setcookie('first_login', 'True', time()+(24 *3600));
I'm checking as below.value is shown in browser application.but prints 'try again'.Is my if condition is wrong
if(isset($_COOKIE[$userName]) && $_COOKIE['first_login']=='True'){
echo $_COOKIE[$userName];
echo 'working inside';
}
else{
echo 'Try Again';
}
You cannot access the cookies until the next request. After you use setcookie PHP needs to finish the request and return the data back to the browser before the cookies are saved. Then on the next request PHP will be able to access the cookie values using $_COOKIE.
setcookie("cookiename","cookievalue", $time); will only set it for the current URL path
Whereas: setcookie("cookiename","cookievalue", $time, "/"); will set the cookie for all pages on that domain.
If you press CTRL+SHIFT+J in google chrome, and click on the Resources tab, you can find the cookies and the path.
I have created a logout.php page to let the user sign out from the website and redirects them to the sign in page.
however what ever i do, the cookies are not getting deleted, so when the user gets redirected to the singin page the latter examines the cookies and then find it, therefore logs the user in.
Below is the code of logout.php:
<?php
unset($login);
if (isset($_COOKIE['xxx'])){
setcookie('xxx', false, time() - 3600,"/");
}
if (isset($_COOKIE['yyy'])){
setcookie('yyy', false, time() - 3600,"/");
}
header("Location: singin.php");
die();
?>
Please note that this php page is in subfolder protected by password and the html link redirects to a php file that require() the logout.php file.
use php unset() to delete your cookie as, you can get the complete details here delete the cookie
if (isset($_COOKIE['xxx'])){
unset($_COOKIE['xxx']);
}
if (isset($_COOKIE['yyy'])){
unset($_COOKIE['yyy']);
}
or, set value as null and a negative time for your cookie as
setcookie('xxx', null, -1, '/');
setcookie('yyy', null, -1, '/');
or, set value as empty and a past time for your cookie as
setcookie("xxx", "", time()-3600);
setcookie("yyy", "", time()-3600);
I have found finally the reason behind the issue.
it's because I have put session_cache_limiter('public'); in my code, so which I presume prevents the client to set the cookie to an expiry date.
I have done that because I don't want the client to ask the user each time they hit back to resubmit the form.
It seems that it's not the correct practice, I'll post another question for that.
Thanks all for the help.
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.
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
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']);