Losing session variables after redirect - php

User fills in username and password.
If it's correct, the page loads some information such as user_id to a session variable.
The script makes a header('Location') redirect.
Somehow the next page doesn't recognize the session... how come?
The redirection is to the same domain, and all pages have session_start();
And I found it more likely to happen in IE than in FF... strange.

Is it possible that cookies aren't enabled?
In order to be able to associate session variables with a specific client instance (ie. how session variables can be used on your browser and my browser at the same time without getting into a conflict), a "session ID" (or "SID") is generated per session. This ID is stored on the server, as well as on the client, usually in the form of a cookie. However, if cookies are not enabled, the session ID is passed along as part of the query string of the URL in each request so that the server can know what session ID belongs to the client.
When you redirect by a header() call, PHP does not automatically insert the SID into the new request, so you will need to append it yourself, in the form of:
header("Location: my_url.com/my_page.php?" . SID)
where SID is a constant defined by PHP that contains the necessary part of the query string (equivalent to session_name() . '=' . session_id(), if a session ID exists).
See Passing the Session ID for more details.

I just had a similar issue, the solution was to simply add an exit(); instruction under the header(..) redirection.

Two thoughts:
Is session_start() located at the top of the scripts, before anything is sent to the browser?
Is the domain exactly the same? www.mydomain.com re-directing to mydomain.com would lead to the problem you describe.

header("Location: my_url.com/my_page.php?" . SID)
exit();
It only worked after I added exit() below the header();

The WordPress documentation states that cookies will be cleared if the user's password is changed. That will kill the session, regardless of whether a redirect happens. So long as you can prevent the cookies from being cleared (and an exit() may do that, as suggested in other answers) than the session should remain.
Note: If current user's password is being updated, then the cookies
will be cleared!
http://codex.wordpress.org/Function_Reference/wp_update_user

I had this problem today and have been searching for a way to fix it. I already had what everyone else has mentioned and could not find an answer anywhere.
Eventually I found the answer after watching my session variables with Firebug. I noticed that on the pages that the variables were being lost, the session Parameter:secure was being set to true for some reason unknown to me.
The fix was to set the secure parameter to false before the session was created.
I accomplished this using session_set_cookie_params. Something like this:
session_set_cookie_params([lifetime], [path], [domain], false, true);

Related

Issues with session_regenerate_id()

I am using Facebook's PHP SDK for validating users to leave comments and it works quite well. Once, validated, I store the user information in a session variable, but first call session_regenerate_id() and then reload the page. When the page reloads, the old session data is still available, including the Facebook SDK state variable, however, the session variable I added is not available. The following is a snippet of the code:
session_regenerate_id();
$_SESSION[...] = ...;
header('Location: ...');
die();
If I take out the session_regenerate_id() then everything works perfectly. Any ideas what I am doing wrong?
EDIT
If I log session_id() every page load, I see that session_regenerate_id() generates a new id and the session contains everything I expect. However, when the page reload occurs, the session id is the previous session id and not the new one, hence I cannot access the new session variables. Why would this happen?
After a lot of logging and scanning the headers being sent and received, I determined that when the initial session was created, the domain used for the cookie was: .domain.com (without the www). However, session_regenerate_id() was setting the domain for the cookie to: www.domain.com. When the browser made a determination of which to send, it always sent the original one, so the session used was always the old one. Once I manually deleted that cookie, everything worked fine.
To ensure this sort of thing doesn't happen again, I added the following before starting my session:
session_set_cookie_params(0, '/', $_SERVER['SERVER_NAME'], true, true);
What is odd, the .htaccess file enforces www.domain.com for consistency, so I am not sure why the initial cookie's domain was set the way it was.

PHP - Session is set after browser restart, but PHP acts as isn't

I've seen various questions like mine, though none provide the correct answer.
I've a PHP script:
session_start();
setcookie(session_name('DSWLogin'),session_id(),time()+2*7*24*60*60, '/');
//This will only be set once (when the user logs in)
$_SESSION['test'] = 'Yup, I am working';
if (isset($_SESSION['test'])){
echo 'Session is set and ready!';
} else {
echo 'No session was set...';
}
and that all works fine except after a browser restart, my PHP script ignores the session.
When my browser hasn't restarted yet, it'll echo 'Session is set and ready!'; just fine.
And when I look into my cookie tab, it indeed says a cookie, named DSWLogin has been set with a certain value.
When I restart my browser, my cookie tab still says that a cookie, named DSWLogin has been set with the same value it had before the restart, so it is still there!
But my PHP script apparently ignores is, and outputs 'No session was set...'...
Thanks in advance,
Isaiah v. Hunen
What you are trying to do is not really the correct way to achieve this. Sessions have two parts, a cookie with a session id set by default to expire at the end of the session (usually browser close) and a server side storage mechanism that is cleaned up automatically after a certain period of time after the last request was received.
What you are trying to do is extend the session to two weeks. While you could change the cookie settings and increase the timeout to session garbage collection doing this is not very reliable.
Instead you want to look at using a one time key stored in a cookie which acts as an alternate login path. This cookie can recreate the session just like a normal login would. There are some details that need to be considered for this to remain secure, but it will do what you are attempting to achieve.
Just because you are setting your session_id in some cookie doesn't mean it is THE session cookie. Most browsers will purge session cookies on browser close. This is what you are seeing. Look at the cookies in your browser that are set when your session is valid and compare this to the cookies that are still remaining after browser restart. You will notice your true session cookie has gone missing.
Quoting the manual:
The session name is reset to the default value stored in session.name
at request startup time. Thus, you need to call session_name() for
every request (and before session_start() or session_register() are
called).
Also if you want to change lifetime of session cookie, use session_set_cookie_params instead of forcing your own cookie.
Also read about session garbage collection and configuration, changing cookie lifetime might not be enough.

PHP Sessions with disabled cookies, does it work?

Today I had skype interview for a job as PHP developer, one of the questions asked was about Cookies and PHP Sessions.
The question was, can PHP session be set and read, used, if Cookies are disabled in users Browser?
I told them not, beacuse PHP Sessions by default depends on setting a session cookie. When PHP session starts, new session Cookie is set with default name PHPSESSID, and that cookie holds value of that session id, for example: ftu63d8al491s5gatuobj39gk7
Then on apache server in tmp folder file sess_ftu63d8al491s5gatuobj39gk7 is created and it holds content of that session, for example: test1|s:12:"SessionTest1";test2|s:12:"SessionTest2";
They told me that's not true, and that you can use PHP Sessions even if user disables cookies in his browser.
Then I told them that you can do that, but then session id would be passed through URL as GET variable. And that's not secure and you must set it up in php.ini.
They were talking how you can use PHP Sessions even if Cookies are disabled in browser. And what if we are building web shop, and some granny uses our web shop and disables cookies and she joust don't care. And that PHP Sessions are great because you can use them even if user disables Cookies. I was like wtf, wtf wtf?!?!
I made test with two files, index.php starts session and sets session variables. And then session.php tries to read that session variables.
This is how it looks:
index.php
<p>This is where I start and set php sessions.</p>
<?php
session_start();
$_SESSION['test1'] = "SessionTest1";
$_SESSION['test2'] = "SessionTest2";
?>
<p>This is a link, that starts new HTTP Request, and tries to read session set on this page:</p>
<p>Read Session</p>
session.php
<?php
session_start();
var_export($_SESSION);
?>
<p>Back</p>
Now, if you enable cookies in your browser, visit index.php, and the visit session.php , session would be printed out.
But, if you clear your browser history and cookies, and then visit index.php, and then visit session.php, you would see empty array right?
So basically my question is, am I right?
Can you use PHP sessions if you disable cookies in your browser?
And do PHP Session mechanism by default, depends on setting a session COOKIE?
Update:
I was going mad about this, so I called back the guy I was talking with. And asked him, can PHP session work without cookies by default? The guy said "yes". Then I told him he is wrong and he said: "yes, yes, if you say so..." and start laughing. Then I told him, ok if PHP session can work without setting cookie, how would server know current user/browser session id, if its not stored in a session cookie? (I wanted to see if he knows that session id can be passed as GET variable) And he was quiet for at least 20s, and told me that he is a System Administrator, and that I should ask that the Developer guy. And that he is 43 years old and has huge experience of 13 years in the bussines (he started with 30? wtf?), but he trusts me on this one. And I explained him how Session work and that you can use it without Cookie but then session id is passed as GET variable, and told him I told them that on interview, but they ware telling me no, no no... :S
So basically, the guy didn't have a clue about PHP and PHP Sessions, and yes he was the one that asked me about sessions telling me that PHP Session can work without cookie, even when I told him it cant be done, and that there is a way to use PHP Sessions without cookies but it won't work by default. He was like, no no no...
At the end he told me that he was thinking that sessions can work without cookies because he, as System Admin on his servers, can never see sessions in tmp folder?!?!?
Anyway, those guys suck at PHP, there is no way I will accept job offer from them, and after all this I dont think they will offer me a job anyway...
Thanks for all the comments!
"A visitor accessing your web site is assigned a unique id, the
so-called session id. This is either stored in a cookie on the user
side or is propagated in the URL. "
Sessions: Introduction
If session.use_cookies = 1 (Cookie enabled.)
If session.use_cookies = 0 (Cookie disabled.)
If session.use_cookies = 1 then session stores the sessionId into cookie. Calling session_id() get the stored sessionId from cookie and saved data into session array will be found on all the pages. If session.use_cookies = 0 In this case session does not store sessionId into cookie and you will get each time a new sessionId using session_id() and data stored into session on other pages will not be found on another pages.
Yes session will work when cookies is disabled.
But first apache check php configuration settings.
Like:
--enable-trans-sid
and
--enable-track-vars
if these value are set true the session will passed by POST automatically.
If "--enable-trans-sid" and "--enable-track-vars" values are set to FALSE, we need to pass session id by using the SID constant.
< a href="index.php?<?= SID ?>" >Navigate from here< /a >
Need to set php.ini
ini_set("session.use_cookies", 0);
ini_set("session.use_trans_sid", 1);
So basically my question is, am I right?
Mostly. In the real world: YES.
Can you use PHP sessions if you disable cookies in your browser?
You CAN use PHP sessions without cookies, as long as the browser identity is obtained somehow and yields a unique value (and this value is passed to the PHP session layer):
session ID in GET (which is the "standard" PHP way if cookies are not allowed, and the "other" way you described). This value is then propagated automatically by PHP, e.g. added to all A HREF's and so on. Where it is not propagated because the automagical link recognition failed (e.g. complex URL built in Javascript), it is your responsibility to provide accordingly.
Or - and here we're not in Kansas anymore:
passed among the nonces with Auth Digest (this is a dirty trick, and of course requires that the whole site is behind an Auth-Digest access authentication scheme. And you can no longer use a "dummy auth" (i.e. http://welcome:guest#www.example.com ) because some browsers, e.g. Internet Explorer, do not support them anymore for security reasons)
recognizing the browser some other way ("fingerprinting") (this is normally(1) suicidal)
Use LSO (Local Shared Objects) to generate a random UUID if it's not there already, and store it so that it can be retrieved on subsequent accesses.
other ways ( see http://en.wikipedia.org/wiki/Evercookie )
(1) if you were in a LAN where you can trust the IPs, you could associate a "session" to the user IP. You might enforce a strict "no cookies" policy in a small firm and still have user sessions without resorting to _GET/_POST for your session ID.
You are right, Session cannot work without cookies.
To illustrate this try doing the following actions.
Login To Gmail.
After login disabled the cookies.
Refresh the page.
You will be redirected to the login page again as the server cannot identify the session.
Now again enable the cookies.
Refresh the page. (Note: Don't click on login button).
You will be automatically redirected to the Gmail inbox.
Hence, we can say without cookies session will not work.
Also, If you are trying to login into the gmail( taking as example you can take any website) with diabled cookies then it will message as "Your browser has cookies disabled. Make sure your cookies are enabled and try again."
If it was me, I would say "Yes"
Since you could store session in form / url somewhere to passed to next page (very bad idea). So, based on his question "can PHP session be set and read, used, if Cookies are disabled in users Browser?"
Then, it should be yes. It can read and used.
However, If user close browser, then it's gone, and that's it. (since that guy didn't ask about this part)
Yes.. It will Work
1.PHP will pass one GET parameter in URL with the name PHPSESSID but it can be changed session.name in php.ini file.
2. It add one hidden input in forms with same name.
You will need to put the session ID in the URL. You will need to make a change in your php.ini file so if you are on a shared host you will need to contact them to see what they will do for you.
// tell the PHP we want to use cookies from the session
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies', '0');
ini_set('session.use_trans_sid','1');
session_start();
// then pass the session ID in the URL(inspect, navigate the network refresh the page you will see in the headers your session ID)

Weird session scope issue in PHP

I am having a really unsual problem I have never had before, I have a signup page/form and a processing page that for submits to, on the processing page I set any errors that are in the user data like empty fields and set them to a session var array
$_SESSION['signup_errors'] = $signup_errors;
$signup_errors is an array that I set to the session, I can then access that session data on the same page but I just changed my site around to use mod-rewrite to change the URL's and the only thing that I can seem to think of is on my signup form I cannot access these session variables anymore and now that I use mod-rewrite the url is like this domain.com/account/new and it used to be domian.com/?p=account.new so now it appears that it is in a differnt folder, could that have something to do with it?
I have tried debugging it a lot and that is the only thing I can come up with is maybe because it appears to be a different directory now because of the mod-rewrite maybe that makes the session unaccessible?
Are you sure you're starting sessions on every page you're accessing? I would check to make sure there's
session_start();
Wherever necessary.
Also, what does
print_r( $_SESSION );
return? Anything at all? If not it would probably indicate what I was saying.
I would check that you're not changing domains. E.G. domain.com -> www.domain.com
Normally a cookie is used to track the session id, and by default, the cookie is tied to a single domain. I.E. If the session was created at www.domain.com, when you visited login.domain.com the cookie wouldn't be sent resulting in no session information.
It happened to me once, maybe you have a similar scenario. The session variable was temporary and I would destroy it once it was outputted to the screen.
With mod rewrite if you are routing everything, if there is a broken image, that might be redirected to your php script as well, it would in the back ground print out the error and destroy that session var.
Just a thought!

PHP Session not working in PHP5

I have 2 pages: login.php and index.php. Both pages start with
session_start();
When I set
$_SESSION['user'] = "name";
in login.php and than open index.php, my session object is empty. How come?
EDIT:
I found the problem: IE 7. I had to grand access to my domain. However, I thought a session is stored on the server, instead of the client? Than why do I have IE grand access to my domain? (http://www.pcwindowstips.com/2007/09/04/how-to-enable-cookies-in-internet-explorer-7/)
I thought a session is stored on the server, instead of the client? Than why do I have IE grant access to my domain? (http://www.pcwindowstips.com/2007/09/04/how-to-enable-cookies-in-internet-explorer-7/)
The way sessions work is that a session cookie is stored for the site, which contains your session ID. The only way the server knows who you are is when it reads the session ID cookie on every page load. All of the $_SESSION data is stored on the server for each user, but the cookie must be set for the server to know which $_SESSION data to retrieve.
This is also why you can essentially "become" another user if you obtain their session id cookie.
Internet Explorers have a stricter cookie policy than most other browsers. Check your session cookie parameters (see also session_get_cookie_params()) and try to replace the default values by explicit values where possible. Additionally you might send a [fake P3P policy](http://msdn.microsoft.com/en-us/library/ms537343(VS.85).aspx) to satisfy the Internet Explorers.
Perhaps this variable in php.ini is mapping to an existing path
session.save_path = "c:/wrong/path"
Here is something that happened to me that might shed light for someone. My session wasn't working properly. IE 8 and Firefox were losing the session information.
I included a file. That included file had an extra carriage return after the trailing &ques?>
That carriage return started the session. I put session_start after the include. BOOM.
Not much info here, I'll try to use my psychic powers.
After the user logs in, do you set the session var and then redirect the user to index.php using an http header? If so, I don't think the session cookie gets sent to the user. If that is the case, the solutions are:
call session_start() when the login form is initially displayed (not just after the user posts back to it); or:
display a "login successful!" message and then redirect with a meta-refresh, or just provide a link to index.php.
You can also try to dump the session ID on both pages, to see if you are somehow starting a new session:
echo 'Session ID is: ' . SID . "<br/>\n"
You need verify if the cookies are enabled and nothing ( this includes blank lines in the beginning or in the end of archive) sent to browser before you call session_start().

Categories