if(isset($_POST['remember'])) {
if(!isset($_COOKIE['tracker_id'])) {
setcookie('tracker_id', $_SESSION['id'], time()+2592000);
setcookie('tracker_username', $_SESSION['username'], time()+2592000);
setcookie('tracker_rsn', $_SESSION['rsn'], time()+2592000);
}
}
I know the code works, because I check to see if there are cookies before I log in, and there aren't. I log in, and there are cookies. I close the tab (not the browser), re-open it in a new tab, and the cookies aren't there. I'm not sure if I overlooked something, but I'm not quite sure what's up here...
Any help is appreciated
How are you checking to see if the cookies are there or not? Checking cookies array doesn't tell you the whole story. If you don't already have it, download the Web Developer Addon for FireFox. It has a feature to view, edit, and delete cookies for the site you are on. View your cookies after logging in. That will give you insight as to what is actually being set by the browser. Then close the browser and open again, visit site, and view the cookies again. See if they are perhaps still there, and just not being read.
I've learned the hard way that it's a really good idea to set the cookie path and domain explicitly rather than letting PHP default it. Otherwise cookies from mydomain.com will have a different path than www.mydomain.com and that can lead to the www cookies not being read from mydomain.com and other fun stuff. We now always explicitly set our cookies, after wasting probably a week's worth of development time over the course of 6 months trying to track that issue down.
If paths aren't the issue you might be inadvertently deleting the cookies. Do the values you are passing in from the SESSION always exist for sure when that code is run? A false value tells PHP to delete a cookie, which could happen by accident if the values are not defined in the array and you don't have a strong error reporting level.
Your code should work as you describe provided that:
1) there is nothing else serverside interfering with the values of the cookies
2) you haven't told your browser to treat all cookies as session cookies
Have you built a test rig with just the minimum code necessary to set and read the cookies? Fromt the snippet you posted, there's obviously a lot more going on in your code. And try to test it in different browsers.
Something like:
<?php
if ($_GET['set') {
setcookie('tracker_id', 'tracker_id set at ' . date('r'), time()+2592000);
setcookie('tracker_username', 'tracker_username set at ' . date('r'), time()+2592000);
setcookie('tracker_rsn', 'tracker_rsn set at ' . date('r'), time()+2592000);
}
print_r($_COOKIE);
?>
C.
Related
I'm working on a simple cookie notice that appears on first visit only and again but only until 30 days has gone by.
The problem that I'm having is the page that is setting the cookie for the entire domain keeps receiving the notice once I go to a different page and then back again, unless I do a hard refresh (CTRL+F5) the notice just won't go away.
In my header.php I have:
$value = 'first_visit';
setcookie("visitor", $value);
setcookie("visitor", $value, time()+604800);
setcookie("visitor", $value, time()+604800, "/", ".example.com");
if(isset($_COOKIE['visitor']) && ($_COOKIE['visitor'] == true)){
// do nothing
} else {
echo '<div id="cookie">By continuing to use our Site, you are agreeing to the placement of cookies on your computer by us and our third party service providers.</div>';
}
So the idea of the code is that the user visits the site and then the page triggers a creation of a cookie, the value of this cookie is not important since the code will simply check to see if one exists, the first time the visitor visits the site, it does not exist therefore they it echo's else, going to other pages other than the page I just visited does // nothing as intended but if I go back to the page that triggered the creation, its still else, unless I do a hard page refresh.
I have also tried:
<?php
if(isset($_COOKIE['visitor']) && ($_COOKIE['visitor'] == true)){
// DO NOTHING
} else {
$value = 'first_visit';
setcookie("visitor", $value, time()+604800, "/");
echo '<div id="cookie">By continuing to use our Site, you are agreeing to the placement of cookies on your computer by us and our third party service providers</div>';
}
?>
I don't think there's anything wrong with your code - ie it's working as expected based on the code. I just don't think you see what the code is actually doing. You say the cookie is eventually set, but you are setting the cookie on a page, moving on, then using back button and getting to a page with that message again. This is likely browser cache, and likely confirmed as you say a hard refresh fixes this.
It seems odd the way you are doing all of this. All I can get from your question and code is you require:
First visit - user sees message and cookie is set
Consequent visits/pages after this - user doesn't see message because cookie is set
The only way you can avoid the browser back messing this up for you is to do a redirect after you set the cookie (eg $_SERVER['PHP_SELF']). but then you can't use the same file to show the message as by then the cookie will be set.
You should rethink this and handle the whole thing differently, but as it stands, with the code you have presented, all I can suggest setting a session.
header.php
session_start();
if (!isset($_COOKIE['visitor']) || ($_COOKIE['visitor'] != true)) {
$value = 'first_visit';
setcookie("visitor", $value, time() + 604800, "/", ".example.com");
$SESSION['displayMessage'] = true;
} else {
if (isset($SESSION['displayMessage'])) {
unset($SESSION['displayMessage']);
}
}
if (isset($SESSION['displayMessage'])) {
echo '<div id="cookie">By continuing to use our Site, you are agreeing to the placement of cookies on your computer by us and our third party service providers.</div>';
}
On the first visit the cookie won't be set so it's set and a session is set, as the session is set it'll show the message. Then on any other page load as the cookie is set the ELSE will kick in and session is unset, and therefore the message is not shown.
(I reverted your cookie checks so you don't have that awful pointless // do nothing ;) )
The above code is very clunky, and I cried a bit writing it. Again, I advise you step back and rethink how you are handling all of this to make it more robust. Separate out your requirements into different files, better use functions, and then call things as and when you need them based on other things being set :)
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've had this twice now. Out of the blue, my log-in system stops working, and by debugging I find out the $_SESSION variable does not survive the log-in process. Then, without an obvious cause, it resumes working. Here's the flow:
User logs in at index.html, form submits to login.php;
login.php does basic sanity, isset and empty checks, then checks the credentials with the database. If the email address and password are correct (i.e., exist in the database) put them in the $_SESSION variable and redirect user to home.php.
home.php retrieves the $_SESSION variables. Here it fails.
The second time (a few minutes ago) I read more about it and found a forum thread I hadn't read the previous time it happened (I stopped reading about it when session variables worked again) which said you need to have <?php instead of <? before session_start();. I tried it, not expecting it to work, but when I logged in, directly after changing that (and that was the only thing I changed AFAIK) it worked. Cause found? Let's check after changing <?php back to <?. It still works. What can be the cause of this and how can I prevent it (or, if it can't be prevented, detect what's going on)?
Edit:
Something interesting: I've got a small utility function to check if the user is logged in:
function assertUserLogin() {
try {
$user = new User($_SESSION['email'], $_SESSION['pwd']);
} catch(Exception $ex){
writeToLog("Exception: " . $ex->getMessage());
header("Location: http://www.korilu.nl/maurits/anw?requested:" . $_SERVER["REQUEST_URI"]);
}
writeToLog($user->email . " logged in\n");
return $user;
}
So I can just do this:
<?
session_start();
$user = assertUserLogin();
?>
On every page the user needs to be logged in. The interesting thing here is, that if it fails (as described above), it calls my function writeToLog() (log() is already taken by the PHP standard library):
function writeToLog($string) {
$log = fopen("log.txt", "w");
fwrite($log, $string);
fclose($log);
}
which is pretty simple. But the log remains empty. (I am sure the function writeToLog() gets called, because I get redirected to http://www.korilu.nl/maurits/anw?requested:/maurits/anw/home.php. The assertUserLogin() function is the only place that does that.)
Try session_write_close(); at all places where the script ends like exit; die(); and page end.
I found out it is a browser-specific issue. It was caused by Google Chrome, I think, because it vanishes as soon as I use mobile Safari or Mozilla Firefox to test the Sessions. Although in the advanced settings I could see the PHPSESSID cookie, it didn't pickup the session.
Important edit
I was wrong. Mozilla started to drop the session too. After I deleted the session (session_destroy()) it worked again though. So my guess is that after the session expires on the server, the browser still has the PHPSESSID cookie. If it sends that to the server, the server can't find the session and just puts an empty array in $_SESSION, leaving me clueless. I hope this helps somebody having the same problem.
Hi
I have problems with Google Chrome, while developing a PHP website.
I start a session, and store a flag inside it. But when I reload the page, the session value is not recognized.
What can be wrong? Thanks for reply.
session_start();
if (isset($_SESSION['chrome'])) {
echo 'SESSION OK';
}
else {
$_SESSION['chrome'] = 'yes';
}
This is simple code, but it doesn't work...
I had the exact same problem with Chrome not persisting php sessions on a login system. Found the following article: https://secure.kitserve.org.uk/content/php-session-cookie-problems-google-chrome-and-internet-explorer which says:
When testing a local site in Chromium, you must either access it via IP address (e.g. 127.0.0.1) or set the cookie domain parameter to the empty string.
I hope this helps.
I had exact same problem, but on IIS and ASP.Net Mvc. An F5 would make the session recover, but moving to another page caused the problem again. I posted the answer for another SO question. Try it out and see if works.
I think the answer to this is to use session_name before session_set_cookie_params. For example...
session_name('MySession');
session_set_cookie_params( 3600*24, '/', $_SERVER['HTTP_HOST'], is_https() );
session_cache_expire(60*24); // cache expire 60 mins
Check to see if you deactivated cookies in your browser.
I have read through the php manual for this problem and it seems quite a common issue but i have yet to find a solution. I am saving sessions in a database.
My code is as follows:
// session
$_SESSION['userID'] = $user->id;
header('Location: /subdirectory/index.php');
Then at the top of index.php after the session_start(), i have var_dumped the $_SESSION global and the userID is not in there. As i said ive looked through the PHP manual (http://php.net/manual/en/function.session-write-close.php) and neither session_write_close or session_regenerate_id(true) worked for me.
Does anybody know a solution?
Edit: I have session_start() at the top of my file. When i var_dump the session global before the header redirect, i see the userID in there, but not in the other file, which is in a subdirectory of this script
I know this is an old toppic but I found the solution (for me).
I've put a exit after the header.
$_SESSION['session'] = 'this is a session';
header('location: apage.php');
exit;
This works for me
#Matt (not able to comment yet...): If:
a) It appears in the session before redirect
b) other keys work
80% of the time the problem is register_globals, and use of a equally named variable $userID somewhere (the other 19% is just overwriting in places one doesn't expect, 1% is unable to write/lock session before redirect and stale data, in which case you could try session_write_close() before the redirect). It goes without saying register_globals should be off :P
I haven't heard of this issue, but I haven't used sessions all that much.
With sessions you MUST do a few things and have a few setting setup:
cookies enabled on client side
session_start(), before anything happens
make sure you don't destroy the session(unless they want to logout)
The PHP session id must be the same (relates to cookies)
Another issue could be the $user->id is returning a reference to an object that doesn't exist on the next page. Most likely not, but make sure.
If I saw your code I could help you a lot more. But when debugging check the session key with session_id() and make sure it's the same. If you could try that then tell me I could keep helping.
I too would like to know how this ends up for when I get back into sessions.
You should start the session before using the session array.
PHP Code,
session_start();
$_SESSION['userID'] = $user->id;
header('Location: /subdirectory/index.php');
Have you got an session_start(); on the top?
Not tested but cant you do something like this:
session_start();
$_SESSION['userID'] = $user->id;
if( $_SESSION['userID'] == $user->id )
{
header('Location: /index.php');
}
I never have this Problem before, interesting
userID does not have any keyword status.
Only reason to me, is $_SESSION['userID'] is being overwritten or deleted somewhere.
Make sure you use session->start() in all the files you want to add/access the session.
One important thing ( which may not be applicable in your case ) is, if the session is being handled using cookie, cookie can be made to be accessible only under certain directory and subdirectories under that.
In your case anyhow, subdirectory will have access to the session.
Make sure both pages are the same php version
(php5, php4 sometimes have different session paths)
I had the same problem recently. I'm writting a customized MVC Website for school and, as everyone told, start_session() must be written in the very first lines of code.
My problem was THE LOCATION of "session_start()". It must be the first lines of your global controller, not the first lines of the view. $_SESSION was not accessible in controller's files because it was only initiated when the server render the view.
Then, I'm using session_write_close() after the header('location: xxx.php') call to keep session variables for the next request.
ex:
globalController.php :
//First line
session_start();
require_once('Model/Database.php');
require_once('Model/Shop/Client.php');
...
logonController.php:
...
//Users is validated and redirected.
$_SESSION['client'] = $client;
header('location: index.php');
session_write_close();
Hope it solved your problems.
This was annoying as hell but I finally figured out a solution.
config.php i had:
include 'session.php';
At the top of session.php, I had:
session_start();
By moving session_start() to the top of the config.php file, viola...
Problem solved!
Another option than killing your script forcefully with exit is to use session_write_close to force the changes to be written to the session store.
This should however not happen if your script is terminating correctly.
As the documentation about session_write_close states:
End the current session and store session data.
Session data is usually stored after your script terminated without
the need to call session_write_close(), but as session data is locked
to prevent concurrent writes only one script may operate on a session
at any time. When using framesets together with sessions you will
experience the frames loading one by one due to this locking. You can
reduce the time needed to load all the frames by ending the session as
soon as all changes to session variables are done.
In my case this only happened during debugging with Xdebug, when I triggered the same script multiple times and thus multiple process tried to manipulate the same session. Somehow the session could then no longer be unlocked.