Best expiration setting for cookies in this situation? - php

I'm creating a relationship table of user sessions (each user regardless of login state gets a new user session unless they already have a cookie denoting the session ID of their current session) and webpages on my site. This will eventually be able to predict interests, in theory.
Now, I've decided that I should use a PHP cookie rather than a PHP session. How long should I set the cookie to be around for? (I currently have it at 24 hours)
Are there any negatives to setting cookies to have a long period of time before expiration? What about non-expiring cookies? How does a major website set cookie expiration times for things like "Most recently viewed items"?

I wouldn't expire them at all (or only in a year or so) if you intend to use the cookies to track users for a long time - as the user visits the page and you find out the cookie data is obsolete, you can delete them using setcookie() (set expiration date to somewhere in the past).
Note that many users have cookies disabled, or have them automatically deleted when they close their browser, for exactly this reason. People don't like to get tracked.

What are you doing to protect from session hijacking? How do you handle people who may visit from a shared computer, do they get the same session?
I would suggest setting up a user login and track information by user. Otherwise, the data you get will not be qualified and can only be guessing at best.

Related

How often should I update login cookies?

I haven’t written the code yet, as I am new to using cookies and trying to wrap my mind around the concept of coding cookies. I’m going to be combing the use of cookies and session data for my login system.
Because there is a time limit set in my cookies, I would think this would need to be updated periodically to keep the cookie active.
My plan:
User Logs in
Cookies are set for user ID, a random token, and a random serial key, and IP address (should I include the IP?)
Cookie data is stored in a database for when cookie is retrieved to validate the information.
I’m setting cookies to be valid for 1 month.
How often should cookie data be updated and when would you recommend updating it?
Should I update every time the server checks to see if user is logged
in or should it be sparatic? Should it only be updated if a session
isn’t found and it checks for cookie validity?
I’m new to this, so any info would be helpful before I start writing this code.
First of all, I would suggest a framework for developing anything in php and I wouldn't try to re-invent the wheel with things like cookies, when frameworks have code to deal with them already - be that Laravel, Codeigniter (in any order).
Setting the cookie for a month should be optional - i.e. give your user the choice whether this is a one time login, otherwise their account may be at risk, say they're using a public computer.
The most simple form, is to update a database whenever a logged in user refreshes a page, based on the session, not the cookie. The cookie is editable client-side, therefore should not be relied on for this updating mechanism. It can be trusted more so for the "remember me" feature, because you can assign specific user ID's to specific tokens/cookie data, meaning that you can then check to see an exact match, if not that means that somebody has tampered with the cookie.
I wouldn't recommend doing both - updating database and updating cookie. Set the cookie once, on login, then just play with a session database.
Not sure I would trust the IP, bearing in mind your IP can now be spoofed and changed via external software, on top of a simple router restart which may assign new IP's on re-connection. It could be an option, but it cannot be the only basis of authentication.
example from comments, clarification:
Say I am a user with ID 1, who has a mobile phone, a tablet and a PC.
Cookies are default valid for 14 days from date and time of login and are only inserted once, and are never updated thereafter.
I have enabled the "remember me" feature on all 3 of my devices as I logged in today -
mobile phone - 17.04.2018 at 12:00
tablet - 17.04.2018 at 12.20
PC - 17.04.2018 at 12.30
We travel to the future, and we the date is now the 28.04.2018.
11 days have passed.
I enable the feature on a new device, my partners phone for example.
The system should automatically remove the "stored" login from my mobile phone, even though 14 days haven't passed (because 3 is the maximum sessions that can be remembered per account).
The example I have provided only makes sense if you want to create a "secure" website which keeps control of not only active cookies but also of previous ones. Obviously, to be more secure I would't even give 3 remember me sessions, but only allow one or two.
If a limit is not what I was after, I would just give the user a settings page where they can deal with other active sessions on their account and give them the choice whether to remotely log those devices out or not.

how to keep the user logged until user log out himself?

I have php login page that stores the user id in the session once the login is successful. User can navigate to different pages or can even close the page briefly and once user re-open the page, he is still logged in. However the problem is that when the user closes the page for longer time, the session get expired automatically and he has to re-enter the credentials and login again.
How can I keep the user logged in forever and log out ONLY if user decides to do so?
I would like the user to be able to close the page, turn off the pc for weeks and when he or she comes back to visit the page, he or she should be already logged in.
Sound like you need to set the cookie expiration date - as per this wikipedia article on HTTP cookies, if you do not set an expiration date for a cookie it becomes a session cookie. i.e. it expires once the browser closes.
There is no real way to specify that a cookie NEVER expires, however you can set the expiration date for some time far in the future.. i.e. in 10 years, and renew that expiration date every time the user loads a page.
setCookie( name, value, expiration )
Another alternative (which would also require some JS on your pages) would be to use the browser's internal database to store the user session id so that you can retrieve the session from your database (I assume you are using some sort of database, otherwise you will run into other issues as explained below).
If I wanted to achieve this I would probably have a piece of javascript on my page loads that checked for the existence of the session cookie, and if not, I would load the session id from the browser's database, drop the cookie, and force a page reload. There are certainly more elegant ways of achieving this, but this should give you an example of how to get this started.
Lastly, please keep in mind that if you don't use a database (i.e. Redis, Memcached, SQL), all you session information is lost when you restart your application server. This is certainly suboptimal, and you should store session information in a database if you want to have this information survive server restarts (or if you have a load balanced environment).
Hope this helps!

Cookie stealing

I have read many answers on stackoverflow, but none of them could answer my question.
Let's consider a case, where a teacher and the student use the same computer. The teacher uses it to upload marks and the student use the computer to browse the marks. Now, the cookies of the teacher are stored and accessible. The student can easily forge the cookies and present himself as a teacher to the system and create havoc.
What approach should I take to disable this? Is this only possible via sessions? Or there exists a possibility with cookies as well.
The main two suggestions I would have are:
Delete the entire session right before the user logs out or logs in. A new session should always be started when authorization level changes.
Only accept sessions ids you generate. By default PHP will accept and start a new session for any value of the session id you send it. If you receive a session id you haven't seen before, discard it and send the user a new one.
If it's not necessary to have the browser remeber the cookie between browser sessions (eg a login can be 'forgotten' if the browser window is closed), then you could NOT set the expiry date on the cookie which makes it memory-resident only.
When the user closes the web broswer, the cookie is forgotten (standard browser behaviour) so there's no link to the old session, and a new login must be provided. The old session becomes "orphaned" and (assuming you have a 'expire through inactivity' process) will be expired eventually.
If you need the browser to remember the last user even if the window was closed, then a short-but-appropriate timeout is needed - destroy the session making the cookie useless after x minutes/hours inactivity (whatever is appropriate).

What is a session cookie?

I was reading this article and I was wondering, what exactly is a standard session management cookie (SSMC)?
It also recommends that the SSMC should be a session cookie and therefore expire when the browser is closed.
Because it's an 'improved' article, I tried to look for any definition in the original article (here).
According to it, a "SSMC handles the credentials for the life of the session, so the newly assigned cookie will not be checked until the next session (at which point it, too, will be invalidated after use)."
What I didn't understand is how long will the user be logged in if the session expires when the browser closes and the session's lifetime credentials are deleted? and how this should be used? There is nothing in the article about the 'normal' cookies (that contain the login information) being session cookies and therefore they should have an expiration date.
I'm really confused so I hope someone can clear it up for me.
Any alternatives as secure as this one are also welcomed. Thanks!
Background:
I'm writing a remember me function using cookies. Apparently there are 2 cookies; The first one is the SSMC (standard session management cookie) and the second one is a login cookie which consists of:
A username
A unique token that's being regenerated every time the user logs in to the site
A series id which is a unique random number for a specific username that never changes. These are also stored in a table in the database.

Session should never expire by itself

I'm using login function in my site with session.
This session of mine gets expired after a few minutes irrespective of whether the user has logged out or not.
Now what I want is that the session should only get expired when a user logs out. If a user doesn't log out his account and then comes back after 2-3 days, even then he should appear logged in.
I have found some examples where they have increased the time for a session to expire but I want that it should only expire on the log out event by the user irrespective of the time he took to log out.
How can I do that?
In particular, is this the right way to do so?
session_cache_expire(0);
session_start();
A solution that is often used, in this situation, is to:
have a not-too-long session duration: it will expire if the user is not active (that's just the way it works -- and that's better for your server if you have lots of users)
when user logs in, you set a cookie that contains what is needed for him to be recognized
if he comes back on the site (with the cookie, and without having an active session), you use the informations contained in that cookie to auto-log him in, re-creating the session at the same time.
This way:
you don't have thousands of sessions "active" with no good reason
you keep the standard way sessions work
And you have the advantage of "never being logged out", at least from the user's point of view.
Also note that with "normal" sessions, the cookie containing the session id will be deleted when the user closes his browser -- so, he will be disconnected, no matter how long the session's lifetime is.
With the solution I propose, you are the one who sets up how long the cookie should remain on the user's computer ;-)
It means, though, that when a user manually logs-out, you have to delete both his session and the cookie, of course -- so he's not immediatly re-auto-logged-in.
Of course, you have to be careful about what you set in the cookie: a cookie is not quite secure, so don't store a password in it, for instance ;-)
Actually, this way of doing things is how the "remember me" feature often works; except, here, your users will not have to check a checkbox to activate "remember me" ;-)
If you don't have the time to develop that kind of stuff, a pretty quick and dirty way is to use some Ajax request on all your pages, that will just "ping" a PHP page on the server -- this will keep the session active (but it's not quite a good way of doing things: you'll still have LOTS of sessions on the server, you'll have lots of useless requests... and it will only work as long as the user doesn't close his browser).
You can't do that with the PHP internal session handling alone. PHP will always send out the session id in a session-cookie which will expire when the user closes his browser. To achieve some sort of auto-login you'll need some accompanying code that sets a longer-lasting cookie on the user's browser and handles the recognition of these cookies and the mapping between the cookies value and the respective user account.
Please note that this greatly affects security issues so you'll have to take care of a lot of things. Please read the following on how a possible auto-login feature could be working:
Persistent Login Cookie Best Practice
Improved Persistent Login Cookie Best Practice
Do you remove your cookies while testing? Are cookies enabled? Do you destory the session somewhere in your code?
Also, see my answer to another post: Quick question about sessions in PHP which explains how to stay signed in. Just don't do a cronjob/sheduled task if you want the user to stay logged in forever.

Categories