I am new to php. I have some silly php session doubts below:
session_set_cookie_params($params['lifetime'], '/folder1');
session_name('MYSITE_SID');
Q1) Above /folder1 means what? will cookie store under '/folder1'? so does cookie looks visible under folder1?
We have a websites like :
www.mysite.com/folder1
www.mysite.com/folder2
Q2) Can I keep same session_name for above 2 folders of same website? or should keep different session names?
Note: If user already logged in 'www.mysite.com/folder1', he should NOT be able to get loggedin automatically in www.mysite.com/folder2
Sorry for stupid queries. but please I wanna learn.
The path parameter in session_set_cookie_params makes the server send a cookie header only when that path exists in the requested resource.Eg:
Set-Cookie: name=Nicholas; path=/blog
In this example, the path option would match /blog, /blogroll, etc.; anything that begins with /blog is valid. So it's not about cookie visibility through out your site but more of when the cookie will be set by the server. Read this for more info.
For your second question, you should use the same session name through out your site as I don't see a practical reason why you would need to change it IMHO. Finally, restricting parts of your site to users has more to do with AAA (Authentication, Authorization, and Accounting) than with sessions.
Good luck!
Related
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)
I like to use PHP to see if a cookie PHPSID27258STATUS is present with the value COMPLETE en if so do stuff.
In google chrome (in Options) I can see this cookie is present and has the value COMPLETE.
If I run this PHP script I get 'Not Set'. What am I doing wrong here?
$cookiename="PHPSID27258STATUS";
if (isset($_COOKIE[$cookiename]) && $_COOKIE[$cookiename] == "COMPLETE")
--update
The cookie is set by "limesurvey" an open source survey platform. Although its probably not the best way. I use limesurvey to have a small survey (iframe) on an site i'm building. I like to let the survey disappear on the next visit when it has bin posted.
Limesurvey runs from the same host (localhost now). And is in a sub directory of the site.
I guess (but there's a lot of code in LS) this is how the cookie is made after an poll/post is completed.
$cookiename="PHPSID".returnglobal('sid')."STATUS";
setcookie("$cookiename", "COMPLETE", time() + 31536000); //Cookie will expire in 365 days
You can only read cookies which belong to the same domain as the reading script. For instance if the cookie PHPSID27258STATUS was set by domain xyz.com, you can not read it using a script on abc.com. So make sure the domain of your desired cookie is the same. Also show us the code part where you are setting your cookie.
Edit:
setcookie($cookiename, "COMPLETE", (time() + 31536000) , '/');
Try setting the cookie with this code:
setcookie("cookiename", "cookievalue", time() + 31536000, "/");
This makes the cookie available to the whole domain, I recently encountered the same issue and when I tried this, it made it work, the reason is, your browser stores cookies for both domain.com and www.domain.com so you never know which your setting and getting from, it's good practice to set the domain even if you don't have this problem.
You cannot access a cookie immediately after you set it. At least last time it was like that. Make sure you do not have this issue. If it is not may be you have a problem setting the cookie, and in that case please post that part as well.
You mention that the cookie is set by a program running in its own sub-directory. You don't mention whether the cookie itself is set to be in that sub-directory, but I suspect this is where your problem is.
If a cookie is set to a path, then it will only be accessible to pages within that path. This behaviour is described in the PHP setcookie() manual page.
When you're setting cookies from a page within a sub-directory, then in order for the cookie to be accessible to the whole site, setcookie() needs to be called with the optional path parameter set to "/".
You state that the cookie is being set by LimeSurvey. I don't know this software, but you should be able to look at the source and see whether it's using the path parameter when it sets the cookie. If not, your best option would be to modify it so that it does. Then the cookie will be accessible to the whole site. (It would be quite understandable if the LineSurvey developers had chosen not to set it for the whole site, because it would allow the software to be run as a more isolated entity from anything else on the site).
I have done a redirection from www.abc.com to www.def.com using .htaccess.
The redirection is successfull but I have a problem whereby the cookies and session can only be accessed when I access the website using def.com.
The session will be missing when it is checked from abc.com.
How to copy or read the session at def.com?
Please Help me.
well you can't do it simply. Maybe see this post ?
Your cookie containing your session id (and therefore, your entire session) is only valid on the domain where it is created. So when you change domains, the cookie is no longer available. To work around this, you could send the session ID to the new domain (which is not very safe, but you might not care), and then creating a new cookie and session for that domain.
This is called "cross site scripting" (XSS) and a lot of people work very hard to make sure that what you want isn't possible. If you do find a way to do it, be sure to let us know, because that would be a MAJOR security breach.
You can only share the same session on both domains when you have access to the session data storage from both servers. Depending on the session data storage type and location, you might need to write your own session storage handler.
Besides that, you also need to make sure that the same session ID is used on both domains. If you want to use cookies for the session ID, you can only do it when your domains share a common super-domain, so they are sub-domains of the a domain like foo.example.com and bar.example.com share the super-domain example.com. In that case you need to adjust the session cookie parameter domain and set it to value .example.com for the super-domain example.com.
Otherwise, like in your example where the domains do only share com as a top level super domain, you can’t use cookies (in the first place). But you can use the URL to transfer the session ID from one domain to the other domain. To do that you need to enable session.use_trans_sid and disable session.use_only_cookies (both at least on the redirection target domain) and append the session ID to every URL pointing from one domain to the other (here you can use the SID constant).
I have two domains. One domain contains the login script. It creates a cookie when logged in. Another domain have a URL shortener.
So, on the 2nd domain that have the URL Shortener script have a file called session.php. Usually I was using $_COOKIE['sessionid'] to get the session id and match it using database.
How can I get the session id now? I have tried few ways but none of them have solve my problem.
For obvious security reasons, you can't read a cookie that belongs to another domain. You can do it across sub-domains though.
Why not append the session id to the forwarded URL?
Have you considered using a SSO implementation?
http://www.jasig.org/cas
http://en.wikipedia.org/wiki/Single_sign-on
We use it at work, it's awesome! It means we don't have to worry about these types of problems.
Cookies are sent by the browser and only to the domain, the cookies were set for.
There is not much (meaning nothing ;) ) you can do.
But if your domains are two different subdomains (e.g. login.yourdomain.com and shortener.yourdomain.com) you just have to set the domain name accordingly to make the cookie valid for all subdomains.
In this case, it would be .yourdomain.com.
You might want to read the documentation of setcookie().
Maybe it is better if you clearly describe what you want to accomplish. Probably there is another solution that does not involve cookies.
Just while setting cookie from the login page
set the cookie to entire domain like this
setcookie("c","value",time()*3600*24,"/");
in this way you can set cookie to your entire domain.
You can't read a cookie from the other domain.
though there are several ways to pass a session id. You can search SO for the cross-domain authorization
The easiest way is to pass a session id via query string
You can't. Cookies are bound to a single domain. You can use cookies across multiple subdomains though.
I have a site which I have been testing in a sub-folder of my client's site-root.
I had no log in problems during testing, but then I moved the new site files from a sub-directory to the main site root, and now I'm losing my logged in state after almost every page refresh in secure areas.
I am running a $_session based login system that refreshes the session id on every page load, with a comparison value stored in the MySQL database.
Does anyone have suggestions for what could be causing this problem?
krico was right in suggesting that the cookie path may be the cause (but the solution proposed seems a bit daft) however you've said that is not the case.
Check to see exactly what cookies (name, path, expiry, flags) are being set and returned by using iehttpheaders (MSIE) LiveHeaders (Firefox) or using a network sniffer like wireshark. Then ask the question again providing details of what you found out.
C.
Cookies are usually path relevant. Your previous sub-directory based site was probably setting the cookie (that binds the browser to the user) only for that sub-directory.
A way to fix it is to put a redirection page on the old subdir that adds a cookie to '/' and then redirects to new site on root.
If you change session id you will loose all data stored in previous session. You must set session name after every session start command
<?php
session_name('AnySessName');
?>
or use other mechanism to store your variables cross sessions.