persist session after closing browser - php

I have an ASP.NET Login App on my site and once logged in, I can navigate to the WordPress(PHP) side (still on the same domain) whilst maintaining the session. See my pastie link below for how this works.
However, the problem arises if I close my browser, I then lose the PHP 'session' despite keeping the ASP.NET session. So I'm 'logged out' on the PHP side but still 'logged in' on the .NET side.
-- Is there a way, using my existing code, to set a lifetime to the session/cookie, to avoid the session/cookie disappearing when I close my browser? --
I have pastie'd my current PHP code from my template's here: http://pastie.org/private/ndcqgbog34uqld1etozda which checks and persists the session.
I did have a look at this example on PHP.net but got confused as to how to use it in my solution.
Many thanks for any pointers with this.

Think you should be using setcookie() with an expiry time (see here). You're only setting stuff in the session (copied from cookies, it looks like, but I'm not sure what their lifetime is).
Instead of this line:
$_SESSION[DOT_NET_SESSION][ $tuple['SessionName'] ] =
$tuple['SessionValue'];
Try this:
$cookie = array($tuple['SessionName'] => $tuple['SessionValue']);
setcookie(DOT_NET_SESSION, $cookie, time() + 60 * 60 * 24);
That should set a cookie for a day, I think.

Related

PHP cookie removal in FireFox 14.0.1

<?php
session_start();
$_SESSION['logged_in'] = false;
setcookie("dsgpassword127", $password, time()-3600); /* expire the cookie */
setcookie("dsgemail127", $email, time()-3600); /* expire the cookie */
session_destroy();
header("location: index.php");
?>
The code above which works very well in Chrome will not remove the cookies in FireFox 14.0.1. I am wondering why this is, if anyone has experienced the same problem or if there is a solution to this conundrum I am in when it comes to expiring these cookies....
According the manual for sesion_destroy():
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. ...If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.
Hard to explain why Chrome is unsetting the cookie, but it's Chrome's behavior that appears to be aberrant, not that of Firefox.
But the presence of an old cookie pointing to a dead session should not be problematic. The server should create a new session - with empty session data - and send back a cookie pointing to the new session.
In fact, saving unencrypted users and passwords on the client is probably ill-advised. Are you sure you need that? Storing that info on the server-side is probably more common, with the client-side only given his the session cookie.
I uninstalled FireFox and reinstalled the latest version which is 15.0. This time when FireFox asked me to remember the password automatically I requested it not do so. Now the browser is reacting normally. I suspect that the same would have been the case also in 14.0.1 in regards to the "Remember password" feature.
Just set the cookie expiration to 1 like so:
setcookie("dsgpassword127", $password, 1); /* expire the cookie */
setcookie("dsgemail127", $email, 1); /* expire the cookie */
Basically the third parameter is the number of seconds since epoch. 1 sets it to 1 second after epoch and so there is not need to worry about time() and all. Check if that helps in firefox.

chrome drops sessions

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.

Properly using session_set_cookie_params

I am trying to implement a login system with a 'remember me' feature . This is my my login page: http://pastebin.com/q6iK0Mgy . In this I am trying to extend the session cookie(PHPSESSIONID) expiration using session_set_cookie_params() . But its not working.
Relevant portion from the code: In this the inner if() loop is being executed , but session_set_cookie_params('3600') is having no effect. I am calling session_name() , as it is supposed to be a requirement for session_set_cookie_params() (according to one of the comments on php manual)
if ( isset($_POST["submit"]) )
{
session_name() ;
echo "calling before checked " ;
if ( $_POST["remember"] == "on")
{
// extend expiration date of cookie
session_set_cookie_params('3600');
echo "<br/>calling after sessions_set_cookie_params" ;
}
}
require_once("includes/session.php"); //session start ?>
I hope I was able to explain what I want to do. Basically what I a trying to do is extend the session_cookie's expiration. is my way of doing completely wrong? is there another way to achieve the same ?
thanks
Never too old for an answer right?
So, PHP is dumb. As in, it doesn't do what you think would make sense.
session_set_cookie_param will not do anything until the exact moment that you call session_start. So if you set cookie params after calling session start, too late. If you set the cookie params but then don't call session_start, nothing happens.
session_start is also a funny beast. It only reads cookie data the first time it is called -well that is unless.... you force it to write, or there is no cookie to begin with. So if there is no cookie, it writes the cookie data and the client saves your session. yay! But when the cookie exists already, how to we force it to write, and therefore update our new expiry date??
So, we have this odd effect of ignoring all of your session_set_cookie_param calls if a cookie already exists on the client. Even better, if you explicitly call setcookie(session_name(),blah blah blah), php will STILL not emit the cookie.
So, let's force php to emit a cookie.
option 1
This works by calling session_id with the only value that won't clobber your existing session. Documentation at http://php.net/session_id states that
Note: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set.
session_id($_COOKIE[session_name()]);
So anyways it's 6 in the morning and I haven't slept yet and you probably figured this out months if not years ago, but what the hell, maybe i'll save someone else the 2 or 3 hours of my life i'll never get back. ha ha.
From the documentation:
You need to call
session_set_cookie_params() for every
request and before session_start() is
called.
Also check http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime

Using cookies with php

I'm just trying to set and use a cookie but I can't seem to store anything.
On login, I use:
setcookie("username", $user);
But, when I use Firefox and the Web Developer plugin Cookies -> View Cookie Information There is no username cookie.
Also, when I try to access the value from a subsequent page using
$_COOKIE["username"]
It is returning null/empty
var_dump(setcookie("username", $user));
RESULT: bool(true)
and
var_dump($_COOKIE)
RESULT: specific cookie does not exist (others are there)
I have done some more testing...
The cookie exists after login (first page) but disappears when I go to another (2nd page) and is lost for good...
Are there any headers that must be present or not present?
http://php.net/manual/en/function.setcookie.php
Try setting the $expire parameter to some point in the future. I believe it defaults to 0, which is in the distant past.
Make sure that you are setting the domain parameter correctly in case the URL is changing after you go to another page after login. You can read more about the domain parameter on http://php.net/manual/en/function.setcookie.php
The cookie is probably expired because $expire defaults to 0 seconds since the Unix epoch. (docs)
Try
setcookie("username", $user, time() + 1200);
which expires 20 minutes after set (based on the client's time).
Use var_dump() on setcookie(..) to see what is returned. Also might do the same to $_COOKIE to see if the key is set.
Thanks everyone for the feedback... Aditya lead me to further analyse the cookie and I discovered that the path was the issue...
The login path was /admin/ and then I was redirecting back to the root...
Thanks all for your help and feedback!

Cookie won't unset

OK, I'm stumped, and have been staring at this for hours.
I'm setting a cookie at /access/login.php with the following code:
setcookie('username', $username, time() + 604800, '/');
When I try to logout, which is located at /access/logout.php (and rewritten to /access/logout), the cookie won't seem to unset. I've tried the following:
setcookie('username', false, time()-3600, '/');
setcookie('username', '', time()-3600, '/');
setcookie('username', '', 1, '/');
I've also tried to directly hit /access/logout.php, but it's not working.
Nothing shows up in the php logs.
Any suggestions? I'm not sure if I'm missing something, or what's going on, but it's been hours of staring at this code and trying to debug.
How are you determining if it unset? Keep in mind that setcookie() won't remove it from the $_COOKIE superglobal of the current script, so if you call setcookie() to unset it and then immediatly print_r($_COOKIE);, it will still show up until you refresh the page.
Try pasting javascript:alert(document.cookie); in your browser to verify you don't have multiple cookies saved. Clear all cookies for the domain you're working on to make to sure you're starting fresh. Also ini_set(E_ALL); to make sure you're not missing any notices.
Seems to be a server issue. My last domain was pretty relaxed on PHP error handling while the new domain shows every error. I'm using both sites side by side and the old one removes the cookie as it should.
Is there perhaps a timezone issue here? Have you tried setting using something farther in the past, like time() - (3600*24)? PHP's documentation says that the internal implementation for deleting cookies uses a timestamp of one year in the past.
Also, you should be able to use just setcookie('username', false); without passing an expiration timestamp, since that argument is optional. Maybe including it is confusing PHP somehow?
How you use cookies data in your application?
If you read the cookies and check if username is not false or not '', then setting it to false or '' will be sufficient, since your application will ignore the cookies value.
You better put some security in cookies value, to prevent user change it's value. You can take a look of CodeIgniter session library, see how CI protect the cookies value using hash. Unauthorized value change will detected and the cookies will be deleted.
Also, CI do this to kill the cookies:
// Kill the cookie
setcookie(
$this->cookie_name,
addslashes(serialize(array())),
(time() - 31500000),
$this->cookie_path,
$this->cookie_domain,
0
);
You can delete cookies from javascript as well. Check here http://www.php.net/manual/en/function.setcookie.php#96599
A simple and convenient way, is to use this additional functions:
function getCookie($name) {
if (!isset($_COOKIE[$name])) return false;
if ($_COOKIE[$name]=='null') $_COOKIE[$name]=false;
return $_COOKIE[$name];
}
function removeCookie($name) {
unset($_COOKIE[$name]);
setcookie($name, "null");
}
removing a cookie is simple:
removeCookie('MyCookie');
....
echo getCookie('MyCookie');
I had a similar issue.
I found that, for whatever reason, echoing something out of logout.php made it actually delete the cookie:
echo '{}';
setcookie('username', '', time()-3600, '/');
I had the same issue; I log out (and I'm logged out), manually reload the index.php and then I'm logged in again. Then when I log out, I'm properly logged out.
The log out is a simple link (index.php?task=logout). The task removes the user from the session, and "deletes" (set value '' and set expiry in the past) the cookie, but index.php will read the user's auth token from the cookie just after this (or all) task (as with normal operations). Which will reload the user. After the page is loaded the browser will show no cookie for the auth token. So I suspect the cookie gets written after page finish loading.
My simple solution was to not read the cookie if the task was set to logout.
use sessions for authentication, don't use raw cookies
http://www.php.net/manual/en/book.session.php

Categories