same logged in user assigned different session ids (in different browsers) - php

I've implemented a mysql-based session interface in php.
I just found out that if I log in to my account using browser A (e.g. Chrome), and then I log in to the same account in another browser B (e.g. IE), each browser is assigned 2 separate session ids. How can I make it such that when I log in again using browser B, I retain the active session of the previous browser A?
The issue at hand is that I'm storing certain information in the session and the data not being synchronised between the same users in different browsers and is wrecking havoc. :S
Is there a way to achieve this?
Thanks!

If you're storing the session in the database, add a mechanism whereby the userId is stored as part of your database's session record, creating what I like to call a "semantic session". When the user logs in, check to see if another session already exists; if so, use session_id() to fixate the new session to the old session's ID, which will join them (and should change your new session's ID for all subsequent requests). Be sure to only perform this action during the login step, or you might end up with freaky race conditions of two sessions trying to be each other and "swapping".

Don't store the data in session, store it in the database.

Sessions are normally identified by cookies, which are only visible in one browser. You could probably use Flash to share the session ID between browsers, but I cannot think of a use case. The point of the session is to store data which is bound to a single browsing session, and not to the user in general. You should use a database or some other form of server-side storage for generic user data.

Related

$ _SESSION and more users - PHP

A very trivial question, but it is a thought that came to me and I don't know if it can be pertinent or not, if for example in the login page, or any other page, we initialize the $_SESSION ['name_session']; and in the logout phase we are going to destroy them, what happens if several users simultaneously use a web portal.
I explain better that we have two users:
user1: enter the portal and the $_SESSION begins
Meanwhile
User2: he also connects
if user1 closes the $_SESSION, could it happen that even user2 will log out?
If, yes, you start the $_SESSION, with the user id it might be a good thing, so would the $_SESSIONs all have unique keys?
PHP sessions are connected to a specific browser session. Each client user gets their own session, and changes made to one session have no effect on other clients.
This is done using a cookie that's sent to the browser. When you start a session, it creates a random session ID, and this is set as the PHPSESSID cookie. When the browser sends back this cookie, it allows PHP to find the corresponding session data.
The session is not shared. Each user (browser / client) has it's own session. A cookie is used to track the individual sessions, as Dharman said. Anything you store in $_SESSION is stored for that individual user and is retrieved again using the session id from the cookie in the next request of that client.
By default, it is saved in session cache (OPcache) and it is not necessary to add the user's id, php takes care of that.

Security in php session cookies

I am trying to understand security when it comes to session cookies in php. I've been reading a lot about it, but I still lack the specifics. I need the basics, someone to show examples.
For example: Do I place session_regenerate_id() before every session cookie? What more shall I think about. I am asking about specifics in code - examples if possible.
Thank you very much.
I am using 4 session cookies after logging in.
SESSION "site_logged_in" = true
SESSION "site_user_nr" = the number of the user to access user_table_nr
SESSION "site_user_id" = the user's id to use when changing data in tables
SESSION "site_user_name" = the name of the user to display on page
When I check if the user has access, I check if all 4 cookies are set, and if site_logged_in is set to true.
Are there better ways? Do I have the completely wrong idea about this? Can users easily be hacked?
In fact you need to have only one session in your website. When you call session_start() session is being created on server and user automatically gets session cookie. Think like session is a some sort of container that placed on the server, you can put whatever you want in that container. However session cookie is just a key to access that container on the server.
It means that you can safely put some data in the $_SESSION and only the user that have cookie with matching session id can read it.
About users being hacked. Yes they can be hacked as long as you don't use HTTPS connection, because cookies and all other data is being transferred in clear text, so if someone intercept users cookie he can access the data stored in the session.
Always use a security token for logging users. This security token could be generated by using crypt(). After logging users in, change the security token periodically until they log out. Also keep the server backup of all the session variables including the security token (in a database). This would also help you to track user login history.
One more personal suggestion: Never use any data from the database as session variables without encrypting it with any of the hashing functions or functions like crypt().
The session information is stored server-side. What you should check is that they're logged in, and that they exists/can log in (in case of deletions/bans).
As you're checking they exist/can log in, you can pull the other information from the database such as name, nr and so on. All you really need is a key called 'logged_in_user' or something that stores the ID of the logged in user. As Alex Amiryan said, the cookie can be copied, so you might also want to store the IP address of the last accessing view in the session, so you can try to ensure security.

How to manage PHP sessions across browsers

I have the run-of-the-mill login-based PHPSESSID mechanism implemented for my web app. One aspect that bothers me is the simple scenario where a user orphans his session in browser A (on computer A), opens another in browser B (on computer B), orphans this to walk back to browser A and so forth. Possibly all this within the (reasonably lengthy) time span for which the PHPSESSID cookies are valid. If both sessions display the user static data, and the user is manipulating this, then the two browsers will not necessarily show data that is consistent with what's in the database.
My preferred response to this scenario is for the second login two invalidate the first. I can keep one PHPSESSID associated with the userID in the database. That's easy enough. Now the hard part: on the second login, how can I invalidate the PHPSESSID that's written into the database such that a subsequent access from the first sessions (with the now invalidated PHPSESSID) will fail?
(I cannot use session_destroy() because that wants to kill the second PHPSESSID, the one I actually want to keep. And I cannot use setCookie() for exactly the same reason.)
One idea I had involves a database access sequence number. Each new request returns the previous plus one. If out of sequence, session_destroy() the current enquirer. Slight inconvenience I see with this is that it requires an extra database fetch to recover the sequence number before each user access.
Is there any way of associating this sequence number with a userID somewhere inside the server's cache that doesn't involve any cookie transmissions?
Thanks.
I don't understand your question completely, but this is how I should do it.
If you store your session data (including SESSION_ID) in the database and you add a user_id to that table, you can delete all session_data of that user before adding the new session initiated on PC B (by that user) to the database. When the user tries to reload his/her session on PC A, the combination of his/her user_id and session_id is not present and you should log him/her out.
I see no problem in this.
On the second login you just write this second login session id in the database.
That makes previous one invalid.

Sessions or cookies?

I'm making a forum for learning mostly but hopefully it will have a couple of users some day.
What im wondering is should you use sessions or cookies for user authentication?
A cookie is a short piece of arbitrary data that the server sends through a header; the client stores it locally and sends it back on the next request. This mechanism can be used to maintain state from one request to the next even though HTTP itself is a stateless protocol. Cookies have two disadvantages: They offer only very limited amount of space (4 kB), and because they are sent back and forth in plain, a malicious client can fiddle with the contents before sending it back to the server, effectively making cookie data untrusted.
A session is a file on the server, identified by a unique ID which is sent back and forth between client and server so that the server can identify the client. The most popular way of sending the session ID is through the cookie mechanism, but it is also possible to pass the session ID through the URL (this is why you often see links that contain the URL parameter 'phpsessid'). This solves the two problems with cookies mentioned above: A file on the server can be as large as required, and the client cannot access the data other than through your own scripts.
Authentication is typically solved using cookie-based sessions; once authenticated, a new session is created, and the user ID is stored in it, and when logging out, the session is cleared and a new session ID is generated. Alternatively, you could store username and password in the session, and check them on every request.
Use a session.
A session is identified by a cookie, true, but not the same as storing user auth info in the client cookie, which is bad for security. A session cookie stores a guid or a hash in the cookie, then identifies the session (either database or file system based, depending on your server's php settings) based on that.
I recommend you store the primary key from your user table, not any other info, then look up the user info every time - this allows you to change their validation status, or security level on the fly while they are logged in; otherwise they will have to log out and back in before your administrative changes take effect for them - IE. you can't boot them.
Also, don't store the username/password, because that requires a less efficient query than by the indexed primary key (even if they are indexed as well).
They are essentially the same, working hand-in-hand. When you create a session..say through PHP, a cookie is created to store the session id too. On the other hand, you would create another cookie if you want to implement a "Remember Me" option to prevent your users from logging in every time.
I'm not a PHP expert, but Session and Cookie are related. In other programming languages you have the option of creating "Cookie based session" or "Cookie-less session". I'm not sure about PHP though so maybe you are referring to different concepts.
I feel using session is much more safe and easy then using cookies. The reasons are as follows:
1) In cookie we can only store a single piece of information, whereas in a session we can store as many information as we want.
2) Being stored on hard disk of user, cookies can be played with. Being a person interested in hacking, I have done that and gathered useful information about the user. Sessions cannot be used for such a thing.
If its a small amount of data (just one variable), I would use a cookie. Here is the code...
setcookie("cookie name", "cookie value or variable name", time+ 3600, "\");
this code sets a cookie that is readable for any of your webpages. It also will delete its self in one hour.
You can also see if the cookie exists like this (to see if it has deleted its self).
if (isset($_COOKIE['cookiename']))
{
}
to collect a value from a cookie...
$value = $_COOKIE['cookiename']; //makes a variable for this cookie for your program

What is the best way to deal with sessions when the user may stay logged in, but a session key needs to be updated, because of another update?

I'm working a site where users could technically stay logged in forever, as long as they never close their browser (and therefore never get a new session key). Here's what I could see happening: a user leaves a browser open on computer A. The then use computer B, login and change their name which is stored in the session. They logout of B, but A is still logged in and still has their old name stored in the session. Therefore, their name won't be updated till the next time they logout manually or they close their browser and open it again and are logged in through the remember me function.
Name is a simple example, but in my case the subscription level of their account is stored in the session and can be changed.
How do you deal with this?
A few ideas that I have are:
After a period of 10 minutes or more, the session data get's reloaded. It might be exactly 10 minutes if the user is highly active as the function will get triggered right at the 10 minute point or it could be after 2 hours if the user leaves and comes back and then triggers the functionality.
Store as little information as possible in the session and load the rest from the DB on every page call. (I really don't like this idea.)
Use database sessions and use the same session on all the computers. I like this, but I could see it getting confusing when something like search criteria are stored in the session--the same criteria would show up on both browsers/comptuers.
For information, even such as the user's name or username/email address, store it in the session, but for other information that would heavily affect their abilities on the site, don't store it in the session and load when needed (attempt to only do it once per instance).
Are there other better methods?
--
Another option: 5. Use database session and when an update is made load the user's other sessions (just unserialize), change the relevant information and save them back to the database.
I would go either with number 1 or number 4. If you store the time of the last update of the information, you could even ask on every request whether the date has been updated.
Don't store information likely to change in the session, if you're looking at scenarios like the one you outline. Just get over your dislike of loading user data with every page - it's by far the best idea.
I'm guessing you don't want to load the data from the database because you're concerned about performance issues somehow. Before you try out any of the other solutions, you might want to test how long it takes to actually load a users data from the database, then check that against your number of users - chances are you won't see any performance problems due to loading user profiles on every page.
Regards
I'd go with option 6: only store userid and session specific stuff (search criteria) in his session and put the rest into APC/xcache (memcached if you're using multiple servers).
this way you'll only have to go to the database the first time (and after the cache expires) and you can still share any data between users sessions.
Normally you should do 2), but you don't like it.
maybe you can use sessions stored in db.
when a user change his name, put into all sessions from that user the information "refresh userdata".
on the next request the userdata is reloaded again into the session and is cached there.
this can be done be reusing your loaduserdata function which called at login.
php session_set_save_handler() - also read comments
php session_decode() - to read the username from the session to store it additionally to the sessiondata. usefull for easily to find the users sessions for updating.
[edit]
don't forget:
when you are updating all the sessions while the page is generated (between session_start and session_write_close) you changes maybe lost.

Categories