Passing session variables with cookies turned off - php

I am trying to pass session variable across the two pages I created. Cookies are turned off on my browser (firefox latest version), but I am getting an error. Here is my code
index.php
<?php
session_start();
$_SESSION['name'] = "bob";
?>
<p>
go to next page click here.
</p>
session.php
<?php
session_start();
echo $_SESSION['name'];
?>
PHP cannot recognize the $_SESSION['name'] index and output the following error
Notice: Undefined index: name in C:\xampp\htdocs\S2\session.php on line 3
Note: I have enabled the trans_sid on the php.ini file session.use_trans_sid=1

I recreated your scenario and what worked for me was putting these settings before the session_start():
ini_set("session.use_cookies", 0);
ini_set("session.use_only_cookies", 0);
ini_set("session.use_trans_sid", 1); // well you can leave this since you have it already in php.ini
ini_set("session.cache_limiter", "");
I hope this solves your problem. Of course you can edit your php.ini too instead of hardcoding this.
What I like to add is that using trans_sid can create a security hole if someone gets your session id. Do some IP check before and limit access to only the IP that created the session id. Keep in mind that using trans_id can also break your app if using an old link with old session id.
Link: https://stackoverflow.com/a/3740866/6622577

One should definitely heed caution that passing around session ids in URLs is a security risk and definitely not advisable.
When setting session.use_trans_sid to true, which is what populates the SID constant, you also need to set session.use_only_cookies to false, otherwise PHP looks for the cookie first.
Reference:
session.use_trans_sid is actually a PHP 4 feature that, when used with a PHP build that had the --enable-trans-sid compile time flag, would transparently populate your relative URLs with the SID constant.
From the manual
PHP is capable of transforming links transparently. Unless you are using PHP 4.2.0 or later, you need to enable it manually when building PHP. Under Unix, pass --enable-trans-sid to configure. If this build option and the run-time option session.use_trans_sid are enabled, relative URIs will be changed to contain the session id automatically.
Also
Note: URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example.

Related

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)

How to convert site from using URL-based Session Tracking to Cookied-based Session Tracking in PHP?

I've inherited a site that uses URL-based Session Tracking.
Here is the session settings via phpinfo():
Here is the code used on every page of the script to initiate Sessions:
ini_set('session.use_cookies', 0);
ini_set('session.name', 'ID');
ini_set('arg_separator.output', '&');
ini_set('session.gc_maxlifetime', 1440);
ini_set('session.gc_probability', 30);
session_start();
PHP seems to automatically append &SID=[sessionid] to any internal link on the site. Furthermore, throughout the PHP script, there are internal URL's manually appended with .'&ID='.session_id().
I assume the previous developer did things this way in order for the site to work on cellphones with no cookies.
In 2011, that doesn't seem to be an issue anymore as almost all cellphones on the market accept cookies. So how can I convert the site back to handling sessions the default way via cookies (specifically, what files would I need to change and how)?
Also, is it possible to have the site handle sessions differently depending on whether the user accepts cookies or not? If so, then how?
It looks like php.ini has the correct setting for use_cookies, so you could remove the first line to enable that, or change it to 1. Looking at the session configuration options, it doesn't look like there's a way to automatically use the URL-based session ID if the browser isn't accepting cookies.
change in your php.ini (or with ini_set) value for session.use_only_cookies to on, that should stop PHP from adding SID to urls
Of course you will also need to get rid of every ini_set('session.use_cookies', 0); an manually appended session_id()

Force php to pass the SID in url - even if cookies are accepted in the browser

I'm trying to get php to automatically pass the session ID via url, even if the browser accepts cookies.
I know url session id are normally considered a security risk, but I have a very specific application in mind which requires several separate users to be able to log in to the same php session, despite what cookie settings their browsers have. Sharing the url is my aim here, rather than a threat.
There will be several "groups" of users, each group should have a unique shared session, so simply applying a fixed session id in the code won't work. I want the "owner" of the group to be able to initiate the session, get a unique id, then pass this on to all the other users, via a url.
As it's an existing application, I can't make modifications that will affect the normal session behaviour for other users - this is for users in a specific group of IPs - which is why i'm trying to modify the standard session handling.
I've tried using ini_set() to disable session.use_cookie, but that simply prevents the session from being remembered at all.
Any suggestions gratefully received.
Have you try enabling session.use_trans_sid ?
Set
session.use_cookies=0
session.use_trans_sid=1
via ini_set() or in the php.ini, .htaccess ...or where ever you can change the configuration settings.
see also:
http://docs.php.net/session.configuration#ini.session.use-cookies
http://docs.php.net/session.configuration#ini.url-rewriter.tags

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().

How can I send PHPSESSID in the URL?

I'm trying to send the PHPSESSID via a HTTP GET variable for a cookie-less client.
I've seen this in various drupal implementations where ?PHPSESSIONID=123ABC is appending to each link, but how do I specify this in PHP and is there any way of changing the GET parameter so it could be ?token=123ABC, or even sent via HTTP POST?
Standard LAMP stack, running the Zend framework.
Thanks!
Using a cookie or not is configured by these PHP options :
session.use_cookies
session.use_only_cookies
If the first one is set, cookies will be used if possible.
PHP should detect if cookies are enabled or not, and use them only if they are supported by the client.
To enable passing of the session id by GET instead of cookies, you might have to activate session.use_trans_sid, which is disabled by default (Which means that, by defaut, session id is only passed by cookies -- never by GET).
But note that, with this option activated, PHP will pass the session id by GET at least for the first page each user of your site will come to... as they won't have the cookie at first, and the only way to check if they support cookies is by setting one, and trying to read it back on the next page.
And users that don't support cookies, including search engines I'd probably say, will have that session id -- and that is not nice :-(
And, you might also want to take a look at session.name to set the name of the key (set to to "token" instead of "PHPSESSID", I mean)
For more details, you can take a look at the Session Handling section of the manual :-)
You can change PHPSESSID using session_name() or session.name in your php.ini file (or using ini_set()).
For cookieless clients, there's the session.use_trans_sid php.ini option - you should be aware that this can cause problems - for example users passing URLs with session IDs in to each other, or search engines picking up such URLs.
Doing it manually:
if ($_REQUEST['token'])
session_id($_REQUEST['token']);
session_start();
print("foo=".$_SESSION['foo']++."<br />".
"link<br />");
print("<form method=POST>".
"<input type=hidden name=token value=".session_id()." />".
"<input type=submit /></form>");
Create a login page, the user must not login without correct id and password.
After logging in the user comes to the home, here user can logout and goes back to the login page.
User must not access home page without going through the login page.

Categories