I am trying to set a cookie like so:
<?php
$cookie_name = "user";
$cookie_value = "James";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<?php if(!isset($_COOKIE['user'])) { ?>
//Do Something
<?php } ?>
but Its not setting, I am using chrome and when I check my cookies, they are not there :(
From the setcookie documentation:
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.
You will not be able to immediately access cookies on the initial page load. Additionally, make sure that you are not outputting any HTML before setting the cookie (protocol restriction).
If you absolutely need to access the cookie immediately, you have a few options:
After setting the cookie, reload the page immediately with header
If this is not what you want to do, you can use JavaScript to set cookies, but you should note that some people disable JS in their browsers. I would not recommend this solution, personally.
$_COOKIE[] variable is set when the page loads, due to the stateless nature of the web.
Here's what the documentation says:
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.
But there are a number of word arounds to access it immediately after setting it.
you can manually set the value for $_COOKIE[] right when you set the cookie to access it or you could use an intermediate variable like so:
<?php
$cookie_name = "user";
$cookie_value = "James";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
$_COOKIE[$cookie_name] = $cookie_value;
?>
if(!isset($_COOKIE['user'])) will return true now.
Another less efficient solution world be to reload the page right after setting the cookie.
like:
$cookie_name = "user";
$cookie_value = "James";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
header("Location: your_script.php");
?>
When the page reloads, if(!isset($_COOKIE['user'])) will return true again.
Hope this helps! :)
As said in the comments, the cookie will not be visible within the same request that set it. You need to do a redirect in order to access the cookie, e.g.
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
header('Location: ' . $your_script_location_path);
exit;
Also, the code inside your check
if(!isset($_COOKIE['user'])) {
// Do something
}
will only get executed when the cookie is not set.
Related
I know this has been asked many times before, and I've read and tried every suggestion I've found.
I set a cookie in a separate file with the following code:
<?php
session_start();
$q = $_SESSION['qty'];
setcookie ("quantity", $q, time() + (86400 * 30), "/");
$_COOKIE['quantity'] = $qty;
if(isset($_COOKIE['quantity'])) {
print_r("set");
}
else print_r("not set");
?>
It print's "set" every time, indicating to me it has been set. However, in a different php page I test for the cookie with the following code...
if(!isset($_COOKIE["quantity"])) {
include("functions/setQty.php");
}
...and it always takes me to the setQty page, indicating to me that it isn't set (which other issues verify that it's not). What am I missing?
I'm trying to access cookie value into html using jquery or ajax ,I'm new to ajax so I don't know how to access json values. I tried with $.getJSON() but it not working. When I execute same code into localhost, it showing john.
test.php
<?php
$cookie_name = "user";
$cookie_value = "john";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
echo json_encode($_COOKIE[$cookie_name]);
?>
Not sure how you are planning on using the value on the client side, but the issue as to why you are not getting output is the fourth parameter option you have in setcookie() function. I'm not sure why you have this as the documentation I found does not list a fourth option. The function accepts the name, value, and time to live.
Also, if all you want to do is return the name of the user value, you don't need to use json_encode(). You can simply echo the name as the response:
<?php
$cookie_name = "user";
$cookie_value = "john";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30));
echo $_COOKIE[$cookie_name];
?>
setcookie(name, value, expire, path, domain, secure, httponly);
When I try to echo $_COOKIE['name'], it print a blank
This should work for you:
<?php
if(!isset($_COOKIE['action'])) {
$cookie_value = "menuopen";
setcookie("action", $cookie_value, time()+3600, "/", ".acvd.com");
}
if(!empty($_COOKIE['action']))
echo $_COOKIE['action'];
?>
You have to look that your using the right name of the cookie also that acvd.com is your domain! And you can't have a secure connection but httponly!
<?php
$cookie_value = "menuopen";
if(!empty($cookie_value))
{
setcookie("action", $cookie_value, time()+3600, "/", "acvd.com", 1, 1); ?>
}
?>
I hope it will work for you.
first Check the cookie name you have used during setcookie method
You can also check your cookie value in browser following are the steps:
1 open debugger tool
2 go to resource tab
3 then go to cookies
4 then go to your domain name
there you will find the cookie name with corresponding value, check for your name is it there and what is the name whether it is name or action.
if name then echo $_COOKIE['name']
if action then echo $_COOKIE['action']
I have this platform which you can login and do your tests (this is a test link): www.mf.pt.la
I can't understand why this isn't working... first I tried this on top of my config.php file:
ini_set('session.cookie_lifetime', 864000);
ini_set('session.gc_maxlifetime', 864000);
Than I tried this with a cookie:
$year = time() + 31536000;
if($_POST['remember']=="1")
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
elseif($_POST['remember']=="")
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}
None seem to work because after 30mins/1h user is logged out! :(
This is very frustrating because inside this website users are usually getting in a out more than once per day, and having always to login is making me lose users actually! :(
EDIT 1:
Ok, so let's see where we are at this point.
After a lot of tests, I have noticed the problem was that I was trying to save an array directly into the cookie and it doesn't work like that. I have searched a lot and created a very simple cookie with name "test" and content "text" and it worked, so if what was working I did created a cookie!
Then I searched for a way to put it working all together on the same cookie instead of save one cookie for each information I needed.
So this is the conclusion. To create the cookie, this is what I've made:
$cookie_name = "remember_me";
$userinfo = $_SESSION[LOGIN_USER]['user_id']."_".$_SESSION[LOGIN_USER]['user_type']."_".$_SESSION[LOGIN_USER]['name']."_".$_SESSION[LOGIN_USER]['email'];
if($_POST['remember']=="1"){
setcookie($cookie_name, $userinfo, time() + 31536000, '/');
}else{
setcookie($cookie_name, $userinfo, time() + 864000, '/');
}
And to call the cookie this is what I have made:
if(isset($_COOKIE["remember_me"])) {
$usercookie = explode("_",$_COOKIE["remember_me"]);
$_SESSION[LOGIN_USER]['user_id'] = $usercookie[0];
$_SESSION[LOGIN_USER]['user_type'] = $usercookie[1];
$_SESSION[LOGIN_USER]['name'] = $usercookie[2];
$_SESSION[LOGIN_USER]['email'] = $usercookie[3];
}
So far, it seems to work, but... let's see if in some more hours the login is done automatically after I enter the website again.
EDIT 2:
Just noticed that spaces are saved into cookie as + and # as %40
EDIT 3:
FINALLY! I did it and here's what I did in order to help future users:
First, let's start by creating the cookie. I inserted a new colum in my users table to save a token, and assigned that token as an encription in MD5 to a variable, like this:
$tokenuser = md5(uniqid(rand(), true));
Once the table was updated, we must create the cookie, and here it is:
$cookie_name = "mfrm";
if($_POST['remember']=="1"){
setcookie($cookie_name, $tokenuser, time() + 31536000, '/');
}else{
setcookie($cookie_name, $tokenuser, time() + 864000, '/');
}
For those who didn't understood that "if" condition, that's simply to check if the user have selected the "checkbox" in order to be remembered "forever" (one year in this case).
So far so good, the next part was the one that was "try and error" until I finally did it! You should put this code BEFORE your headers, because otherwise it might not work and will probably give you an error:
if(isset($_COOKIE["mfrm"])) {
$usercookie = $_COOKIE["mfrm"];
}
So, this way your variable $usercookie now has the content of your cookie (the unique token we created).
"Later" on your code, you simply do a call to your database, check for which user that token is valid and then just asign user_id and all other things you want in order for user to have his login. :)
I hope whoever sees this can solve the problem, I did a LOT of Google search before I finally get this working.
My suggestion is, do a lot of "print" and "echo" in PHP so you can see where is your problem, if needed stop your code by inserting sleep(2); (where 2 means two seconds)
Good luck! :)
This won't suffice, cookies are saved in user's browser, so every time she connects, you check her cookies and and set set up her session accordingly.
Hope this helps
=== EDIT ===
This may help you: http://www.pontikis.net/blog/create-cookies-php-javascript
Let's say that the user ID is '12345', and he is logging in
You set the cookie with:
setcookie('user_id', '12345', time() + (86400 * 30), '/');
Then, then if the user logs in tomorrow, and his session has expired, you check if his user_id exists in DB from the cookies:
if(isset($_COOKIE['user_id'])) {
// check the user_id in DB and create session if exists
}else{
// User has no cookies, then he has to login
}
Hope this makes sense.
This is a very simple example, so of course, do not just put a user_id in your cookies, but a more rigorous form of authentication, like the last session id and a token you'd have generated.
=== EDIT2 ===
Is 'remember' the name of a checkbox? Because in which case, if it is not checked, $_POST['remember'] is not set. So instead of checking the value of $_POST['remember'], you should check if it is set or not
Assuming that 'remember' is the name of a checkbox:
$year = time() + 31536000;
if(isset($_POST['remember']))
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
else
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}
I am currently setting a cookie on a PHP page of my subdomain
$asdasd = "1";
$expires = time() + 86400; // 1 day
if (($username == $actualusername) && ($password == $actualpassword))
{
setcookie("loggedin",$asdasd, $expires);
header('Location: exampleurl');
}
I am then trying to read it on another page on the SAME subdomain:
var_dump($_COOKIE['loggedin']);
nothing is returned - even though I can see the cookie set in the browser privacy settings.
Any ideas?
Thanks
the issue must be around path where you set your cookie, in your case solution would be
setcookie("loggedin",$asdasd, $expires, "/");