PHP Sessions with disabled cookies, does it work? - php

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)

Related

PHP - How to store user's preference (Mobile or full site) without using Cookies

I need to be able to load the user's previously set preference (within the same session, doesn't have to persist between sessions) of if they want to view the mobile version or full version of the site.
I would like to achieve this via a cookieless approach, however I am pretty sure that storing stuff in the $_SESSION variable will write to a cookie.
Is there a better way of doing this?
Thank you!
Xavier.
You can disable cookies for the session:
ini_set('session.use_cookies', 0);
ini_set('session.use_only_cookies', 0);
ini_set('session.use_trans_sid', 1);
this will force any client to append his session-id to every request he makes in order to authenticate. (Well actualy your server will append it to any generated link, so the client includes it automatically)
However, this has several drawbacks:
The session could be "copied" to other clients, when the url containing the session id is transfered.
Closing the browser and reopening it does reset the session.
Navigating away from your website may list a valid session id in the "referer" of another server - which might show it somewhere, so any unknown person might get access to the (maybe still valid) session.
First of there is 2 kinds of cookies.
The dreaded client cookies.
The sessions cookies. A session cookie is only a unique hash set by the server to identifiy the users session (not the user!), you could achive the same thing by adding a query parameter to every link on the site with a number for the session.
The $_SESSION variable contains the variables you set on the server linked to the users session.
You can disable the session cookie and only use query parameters in php.ini

php PHPSESSID exists but session destroyed

I am trying to login an user for 2 weeks if user login with remember me check then i have set some variables in session and cookie set for 2 weeks. It is set correctly i have printed it and got the value session_cookie_lifetime = 1209600 and session_gc_maxlifetime = 1209600. I also print session and got correct value in $_SESSION.
After login in my site when i shut down my computer and reopen my site it seems that it is working (it is keeping me as login user). But when i shut down my computer and next day when i open my browser it is not working and it is showing that i am not login on my site. I have printed $_COOKIE and $_session . It shows that in cookie there is :
[PHPSESSID] => svikos35bgclmebk2cqraiddt2
But session is empty.
I got this form modx stuff:
MODx automatically starts and ends sessions with each request made to the site. You can simply save values into the $_SESSION array and they will be saved in between requests so you can use them on subsequent pages (so long as you have the same user session). Not really any magic to it other than don’t call the session functions yourself to start, end, or otherwise manipulate the session configuration—that can all be done via settings in MODx.
I am using modx revo. It is a bit descriptive question. let me know you need something else.
Anything that may help me (blog link,any settings, any suggestion ) will be highly appreciated.
Thanks in advance
This only happens after a day?
Could tmpwatch be deleting session files from the server?
session_cookie_lifetime and session_gc_maxlifetime doesn't garantee you, that session will be saved for a week. GC kill unused sessions. Check PHP documentation about this parameters and you see, that you can't be sure, that your session will be on the server and you don't be sure, that your sesssion will be destroed after this time. GC is async.
You need to recreate $_SESSION after login (and autologin) if it doesn't exists.
Check this article (in russian, try google translate:
PHP GC: unexpected behavior
The basic idea behind SESSION is that, When you create or call session_start() method your server generate a session id and store it on server memory. Also the server create a cookie on your client machine that cookie contains an id that is related to your server side session id. When you call session_destroy() method server delete that id on server side but the client side cookie doesn't. That is why your session id still shown. You can also check by cache and cookie clearing. When you clear cookie your session will destroyed.

How to do session fixation?

Can someone explain me how session fixation really works? On my localhost server I uploaded file with this code:
<?php
session_start();
if (!isset($_SESSION['count'])) $_SESSION['count'] = 0;
else ++$_SESSION['count'];
echo $_SESSION['count'];
?>
I set in my browser address: http://localhost/sessiontest.php?PHPSESSID=1234
It will begin just with 0 writen, after few times pressed refresh button it will go to 1,2,3,4,...In book and on internet topic I read before, there'written that if I use this adress in browser in different browser or in diferent PC, it will show the number mz first browser ended with. However when I typed this address to second PC, it was begining from 0.
Is it somehow secured in higher version of Apache and PHP or did I totally misunderstood the topic? Thanks for help!
I think you may have misunderstood. PHP uses PHPSESSID to store the ID of a session. Normally this value is stored in a cookie, but it can also be stored in the url if cookies are disabled.
If you read the value of the url (or the cookie) on one browser, you can use that value in the url in another browser to effectively take over that session. That is because PHP doesn't track any information, but just uses that session id to identify a session.
I guess in your case, cookies are enabled as well, so PHP uses the stored cookie rather than the URL value. You can try to delete the cookie first, disables cookies altogether and use this url, or you can change the value of the cookie.

PHP SESSION (using myPajamas login scripts) not working when changing networks

I have looked everywhere on the web, and the nuances of SESSION variables need some clarification for me.
I have a website that sets a session variable (I assume it also sets a cookie defining what the session id is? Not sure how that works), and all works perfectly. What I've found when roaming(using wifi) by cellphone, that whenever the phone switches wifi networks, the browser seems to be unable to access the session anymore until that window/tab is closed and reopened.
From what I've read the following apply, please clarify for me:
When browser windows are closed, the session cookie is destroyed, thus when I reopen it, a new cookie is created attached to the new session id. Thus allowing the session to work properly again?
If the network is switched, the server creates a new session id, but because the browser window wasn't closed, the old session cookie wasn't destroyed, and the browser tries to manipulate an expired session id (the old one the session cookie contains)? No idea if this is true, I have read a ridiculous number of pages on this and I can't find anything specific. But this is the impression I get. I have seen so many warning about session_regenerate_id() that I am very nervous about using it...
Any help on details about this, or ways to fix it would be extremely helpful. I am at my wit's end...
UPDATE
I am using a mypajamas script to facilitate logins. The sessions are created normally. However, after looking through the code, I found a place where a session variable is set for the $_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_USER_AGENT'] values. They are then cross referenced to ensure it's the same user on the same browser on the same IP. It was done to prevent multi-source attacks (make a hijack unlikely). The problem is when using mobile browsers, or dynamic IP's the IP can definitely change, and authentication fails.
I can't believe I couldn't figure this out, I spent hours looking for issues regarding session id's changing.
Hopefully it helps someone with a similar issue in the future. And a sincere appreciation to all who read this post, your guidance in the comments definitely helped me troubleshoot this.
EDITED CODE
class.mypajamas.php
From:
function check_ipau() { // user visits again... but is it really him? check values set above (by get_session())
if( $_SESSION['auth'.$this->_unique_id]['ip'] == $_SERVER['REMOTE_ADDR']
&& $_SESSION['auth'.$this->_unique_id]['ua'] == $_SERVER['HTTP_USER_AGENT']) {
// session data is correct -> user did not "change" ip-address or user agent (aka; hijack is unlikely)
return true;
}
else {
return false;
}
}
To:
function check_ipau() { // user visits again... but is it really him? check values set above (by get_session())
/*if( $_SESSION['auth'.$this->_unique_id]['ip'] == $_SERVER['REMOTE_ADDR']
&& $_SESSION['auth'.$this->_unique_id]['ua'] == $_SERVER['HTTP_USER_AGENT']) {
// session data is correct -> user did not "change" ip-address or user agent (aka; hijack is unlikely)
*/
return true;
/*
}
else {
return false;
}*/
}
First of all, session variables are actually cookies.
1) Session cookies have a lifetime. If your code isn't specifying the lifetime, then the value defaults to whatever is in your php configuration. Do a phpinfo(); and look for session.cookie_lifetime, which is a value in seconds. A value of 0 means the cookie expires when the browser window is closed.
2) If your code is using boilerplate PHP Session handling, then it's unlikely that the issue is related to the user's ip address changing. PHP sessions do not store client ips, and as long as the application you're connecting to has the same domain name/public ip across both networks, then you should be fine. (see PHP Session Cookies fail with users changing IP)
It's possible that there may be some added Session handling that stores the client's IP, but that would have to be custom coded and not based on any built-in functionality.
(based on your edit, this was, in fact the case.)
If you're accessing the same url on network A and on network B, then there is no reason why the session will change / be affected by the network switch. If you have to close the browser window down, and find that your session data is gone, then the problem simply lies in setting the lifetime of the session cookie to be a value other than 0. Place the following line before session_start():
session_set_cookie_params(X);
Where X is a value in seconds after which the cookie will expire. Keep in mind that if you call the aforementioned code before every instance of session_start(); then the cookie will effectively never expire since every single page will be resetting that counter ahead by one hour.
Sessions are server-side only. Unfortunately, if you are coming from a different network address the session will not be valid.
A good practice if you want to retain session values is to create your own cookies, so that you know someone was once authenticated/had a valid session. You then first check if the session values are set, if not check for that cookie. If that cookie exists and has a good value, you can re-set the session value to that of the cookie (or just set the session as you would upon authentication). If there is no session and no cookie then the session is presumed to be non-existent.

What is PHPSESSID?

I'm playing around with cookies. And I dont have any cookies called PHPSESSID.
Do i need it? Can i remove it?
Whats the "function" of it?
if (count($_POST)) {
setcookie("TestCookie", htmlspecialchars($_POST['val']), time()+3600);
}
print_r($_COOKIE);
Prints:
Array
(
[TestCookie] => blabla
[PHPSESSID] => el4ukv0kqbvoirg7nkp4dncpk3
)
PHP uses one of two methods to keep track of sessions. If cookies are enabled, like in your case, it uses them.
If cookies are disabled, it uses the URL. Although this can be done securely, it's harder and it often, well, isn't. See, e.g., session fixation.
Search for it, you will get lots of SEO advice. The conventional wisdom is that you should use the cookies, but php will keep track of the session either way.
PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.
It's the identifier for your current session in PHP. If you delete it, you won't be able to access/make use of session variables. I'd suggest you keep it.
Check php.ini for auto session id.
If you enable it, you will have PHPSESSID in your cookies.
PHPSESSID is an auto generated session cookie by the server which contains a random long number which is given out by the server itself
Using cookies in PHPv7.4 and Microsoft Edge browser, PHPSESSID only seems to be generated when first loading/initializing a web app. If I remove the cookie the browser setting (but keep the web application tab open), it kills the session and forces me to login again. However when I log back into the web application the PHPSESSID cookie does not regenerate and yet I still have my session variables working as expected.
I was testing this because I have a web app that loads an external form (from another site) within an iframe and when the form submits and redirects back to my web app (within the iframe) it loses the session within the iframe. Removing the PHPSESSID cookie fixed the problem of losing the session, but I'm not sure why the cookie is the problem (but that is for another thread).

Categories