multiple condition for cookie variable in if statement - php

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.

Related

Why PHP Cookie variable is not saved after closing Chrome

i'm learning to use cookies in PHP. I was expecting that every time i set a cookie, the cookie and all of his variables are stored on the client site so i could use them again next time the user will visit the site. Anyway in the next example (a web application with a sign in option, i use cookies to store a unique string so i could implement "Remember me" option) i can access the id of the stored cookie but the variables data seem lost. Here is example of the code i use and screenshots of what i get.
Setting up a Cookie
if (isset($_POST['remember_me'])) {
$token=uniqid($_SESSION['id']);
$sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
$conn->query($sql);
setcookie("remember_me", $token, time()+30*24*60*60*1000);
}
else{
setcookie("remember_me","",time()-1000);
}
User page
On the user page it just simply prints out the $_COOKIE and $_SESSION array.
<?php
echo "SESSION: ";
print_r($_SESSION);
?>
<br>
<?php
echo "COOKIE: ";
print_r($_COOKIE);
?>
Process:
First i delete all the cookies using the advice i found here:
how to delete all cookies of my website in php
Then log inside Log in screen (this form call a script that execute the code for setting a cookie i gave at the beginning, then redirect to the user-page) User page before closing
Close the browser and open it again directly at the user-page (without executing other scripts /localhost/MIAFormApp/script/db/HTML_PROBA/user-page.html.php User page after re-opening
What did i get wrong and why the cookies array after re-opening is empty?
EDIT:
The second time i open browser the script for seting the cookie is not executed. I just set the url to go to the user-page.php .
Examp:
/localhost/MIAFormApp/script/db/HTML_PROBA/user-page.html.php
Try deleting the else statement in your sample code - meaning go from:
This
if (isset($_POST['remember_me'])) {
$token=uniqid($_SESSION['id']);
$sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
$conn->query($sql);
setcookie("remember_me", $token, time()+30*24*60*60*1000);
}
else{
setcookie("remember_me","",time()-1000);
}
To this
if (isset($_POST['remember_me'])) {
$token=uniqid($_SESSION['id']);
$sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
$conn->query($sql);
setcookie("remember_me", $token, time()+30*24*60*60*1000);
}
When you re-open your browser, the if statement is going to check whether or not the POST variable remember_me was found. The only time that it will be found is when someone logs in because the login form is sending that information on form submit. In every other instance ( such as re-opening the browser), the else statement will be executed which isn't what you want. The reason being that setting an empty value on a cookie will delete said cookie.

I can't delete cookies PHP although path and time was set correctly

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.

Check if user has logged in with right password OR has a cookie using PHP

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.

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

Check if a PHP cookie exists and if not set its value

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']);

Categories