Cookie will set, but won't remain set - php

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?

Related

Cookie warning alert doesnt dissapear on first click

I created this Cookie alert bar for my site, it works as intented. But you need to click the close link twice to close down the warning for some reason that I cannot figure out.
I use this following function to check if cookie exists or not.
function checkIfCookieExist($cookieName) {
if(isset($_COOKIE[$cookieName])) {
return true;
}
else {
return false;
}
}
if cookie does not exist, and the cookie get parameter exists and equals 1 I create a cookie
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
}
Prints out the cookie bar, links to index with a get parameter for the cookie
function renderCookieBar() {
echo('
<div id="cookieBar">
<p>blabla cookie, cookies on this site yo</p>
I understand, close this box!
</div>
');
}
Calls function to print out cookiebar at given place in my html code
if(!checkIfCookieExist('cookieConfirmation')) {
renderCookieBar();
}
I appreciate any answers or help,
Cheers!
When you set the cookie in the header, the cookie is not directly present; means: the cookie is available up on the next page hit.
Check the manual: http://php.net/set_cookie
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 can either
1. Set the cookie and immediately reload the page
Set the cookie and force a browser refresah by using header("Refresh:0");.
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
header("Refresh:0");
}
2. Use Javascript
When setting the cookie with JavaScript it is directly available from the browser. You may also rewrite your script, so the JavaScript sets the cookie and removes the notification bar.
There are many solutions (also here on SO) how to work with cookies in JavaScript easily. If you are using a JavaScript library like jQuery you also have plugins handling the cookies.

Cookie is not setting in PHP

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.

The Cookie set is not detected

Hi guys i set a cookie using my script known as cookieset.php
setcookie("atid", $atid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
and it is shown in the browser
Name atid
Content 1234
but when i try to retrieve it like this from another script
echo 'value is: ' . $_COOKIE['atid'];
it gives the error saying
undefnied index: atid in.........
can anybody help me over this
setcookie("atid",$atid,time()+315360,"/");
// use
if (isset($_COOKIE['atid'])) {
echo "cookeies set ";
} else {
echo "cookeies not set ";
}
use mozila firebug / cookies to see cookies file
The $_COOKIE array is populated with information sent from the browser. The first time you request the file that calls setcookie - cookieset.php - the server sends the cookie to the browser, but at this time the $_COOKIE array was already populated without the cookie you just set.
The cookie will be available in subsequent requests until it expires.
To see the cookie in PHP, just do like this.
if (isset($_COOKIE['atid'])) {
echo 'Cookie found with value ' . $_COOKIE['atid'];
} else {
setcookie('atid', $atid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
echo 'Cookie was set. Please refresh to see it working';
}
The problem (from the error), seems to be that $_COOKIE['atid'] (depending on what line the error is at) is undefined - that means it has not been set, and seeing that you actually set the cookie, I am saying that its the atid that is undefined. Make sure you are getting it, check with isset()
Try this :
if (isset($_COOKIE['atid'])) {
echo $_COOKIE['atid'];
} else {
echo "No cookie Set";
}
And one more point :
it won't be available until the next page load or by doing the page request again.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

Why doesn't my cookie get set

Im trying test the cookie that are set in my browser, earlier cookieid was given inside the url(mydomain.com?cookieid=1234). now im trying to set a cookie by calling the script which sets it. when i load the script known as proceed.php, i want that to go on and set the cookie as i have written. but it does not set the cookie as i intend
proceed.php
<?php
$cookieid = 1234;
include('bin/setcookie.php');
?>
setcookie.php
<?php
include_once dirname(__FILE__).'/../Lodread.php';
$cookieid = isset($_REQUEST["cookieid"]) ? floatval($_REQUEST["cookieid"]) : 0;
$project_id = isset($_REQUEST["projectid"]) ? intval($_REQUEST["projectid"]) : 0;
if (isset($_SERVER['HTTP_REFERER'])){
$urlParts=parse_url($_SERVER['HTTP_REFERER']);
if (isset($urlParts['query'])){
$vars = parse_str($urlParts['query']);
if (isset($vars['cookieid']) && floatval($vars['cookieid']) > 0 ){
$cookieid = floatval($vars['cookieid']);
}
}
}
if ($cookieid) {
if ( ! isset($_COOKIE["cid"])){
$cid = ($project_id?"$project_id:$cookieid":$cookieid);
setcookie("cid", $cid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
header('Location: '.Config_Reader::readProjectConfig('Cookie')->base_url.'/set2.php');
}
}
?>
This is sample, try like this.
How to Get the Contents of a Cookie:
Cookies set for a page can be retrieved from the variable $_COOKIE['cookie_name'] where 'cookie_name' is the name of the cookie you set earlier.
For example, if you wanted to display the value of the "userlogin" cookie, the following code should do the trick.
echo "Welcome back to the site" . $_COOKIE['userlogin'] ;
Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:
/* WARNING: THIS WILL NOT WORK */
setcookie ( "userlogin", "anonymous", time()+60 );
echo "Value of userlogin: " . $_COOKIE['userlogin'] ;
Set Cookie without "mydomain.com".
use this:
setcookie("cid", $cid, time() + 60 * 60 * 24 * 365, "/");
now you check cookie set.
Try it without specifying the domain when using the setcookie function. Also, I would recommend passing $cid directly to your header function since the cookie value can't be retrieved within the same php script right away. Then finally you can see if the cookie is set for future use by using $_COOKIE['cookie_name'] in a separate php script to get the cookie's value.

Can't make users login for long period of time

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);
}
}

Categories