Setting sessions in cookies and retrieving the sessions from the cookie PHP - php

Is it possible to set a cookie with the session that has been created and with the session ID and then retrieve the session from the cookie next time you visit the page. I am trying to make a remember me button on my login page and wondered if this could be done this way.

Do not try to prolong a PHP session in order to build "Remember Me" feature. It's much better to re-initialize the session.
The most common scenario is this:
When a user comes to a website with checked "Remember Me" checkbox, the website generates a unique code (a pretty long random string) and stores it in the cookies and a server side database.
When the user closes a browser the session closes, but cookie stays.
The next time the user comes the server will see the cookie, find it in the database and authenticate him based on the code instead of user/password pair.
This would be a good starting point, but in addition there are several enhancements are possible:
You could save a username in the cookie along with the unique code. It's safer and faster to authenticate using this pair.
You could save a user's IP in the database, so that authenticating data will work from this IP only.
Instead of generating the unique code and saving it to the database, you could build the code on the fly as a hash based on user password plus salt. This saves your database from write operations.
Based on security/speed requirements there could be variations of this scenario, but the base stays the same: mark a user using cookie, re-authenticate him once he comes back.

Related

Implementing a "remember me" log in system using cookies or sessions

I want to implement a "remember me" feature on a website I am currently working on, so that when a user closes the browser and open it again, he will still be logged in with the same user.
What i currently have is a log in page that creates a session when the user logs in. What I want to do is to create a cookie that saves information about the user that allows me to identify him.
Now there are a few thing that I need your help about:
I don't want to save any sensitive information in the cookie, such as passwords or even a username. What i though to save is the session ID created when he first logged in, and save it in a table on MySQL database. Is that a good idea, or is there something better that i can save on the cookie?
After I implement the "remember me" feature, will I still need to use sessions? What I mean is, that the website have the option to use it without a user, so of course on every page of the website I will have to check if the user have a cookie stored. If he does I will automatically log him in, but should I do it using a session? isn't it a duplicate that I use both cookies and session for the same purpose, and of course do it for every single page of the website.
By the way I am developing the website using PHP.
It doesn't really matter. Only I would refrain from reusing this value as a session id again.
Yes, you will still need sessions, unless your site is extremely simple.
You can store the md5 of the cookie in the database...but just remember. If a user has multiple devices you get a cookie for each device.
If you don't clean your table once in a while it's going to contain lots of data!

Persistent login using cookies and session variables

I've been researching the best (and safest) ways to implement persistent logins on my website, and I've come up with the following:
When a user logs in, a cookie is created containing the user's ID/username, and a randomly generated number (token). The token is stored in a relational table along with the user ID/username. Every time a members-only page is loaded, this cookie is checked against the relational table, and if it exists and matches with the token, the login is valid and the page can load. If not, however, then the login is invalid, the cookie is destroyed, and the user is prompted to log in.
I was thinking... to save on database access every single time a page is loaded, I could also have a session variable that lasts, say, 10 minutes, and is destroyed automatically when the browser closes. If the session is alive, then it's refreshed and the user can proceed. If the session expires, but the cookie is still valid, check the cookie, reset the token, store that new token in the database (while eliminating the old token, or storing it in an archives table for future reference), and reset the cookie using the new token value.
However, what would the session contain? And how could the session not simply be faked with some JavaScript? Perhaps the session contains a one-way encrypted hash? What would be used to generate that hash (user ID, etc.)?
I'm kind of stuck on where to go from here. I get the cookie stuff, but using temporary sessions (to avoid repeated calls to the database every single time a page is loaded) eludes me. Any help? Thanks.
Cookies should be fine (an alternative would be to store it in the HTTP header), however I don't see the need to store the username/ID in the cookie. The token itself should be enough. You can use a UUID as a token. Store that along with the username and a last_access_timestamp in the database table. And only send the token (in a cookie or in the HTTP request header) on every request. That's enough for implementing sessions in my opinion.
A token is generated on a successful login of a user, stored in the database and passed to the user. Whenever a user accesses the webpage, the token is passen in the request and is validated. If valid the last_acces_timestamp is refreshed and the user can proceed. The lookup in the validation will be done by token and with the username you can do the authentication and authorizaton. If token is invalid or expired, forward the user to a login page.
Deleting expired sessions out of the db can be done periodically using a cron job or on creation of a new session.
For performance reason you might think about storing the session in a hashmap in memory. Since it might be costly to always update the database.
Also think about using HTTPS, to prevent people sniffing the token.
I have solved this the following way, few months ago:
https://stackoverflow.com/questions/12829994/java-custom-session-implementation-expired-sessions
Usage of UUID is not recommended according to RFC 4122 it is stated that
Do not assume that UUIDs are hard to guess; they should not be used as
security capabilities.
I would recommend combining and multiply all of the following information together into a hash with also encrypting it using a public key stored in your server.
UserId (Or User UUID that was generated for each user while registration)
Encrypted His/her password (considered as a private key for encryption per each user)
Time stamp
Client Operating System
Client User Agent (Browser name)
For storing tokens, you could use either memcache which is used heavily in big companies or redis if you are focusing on persistence.
Keep sure that your cookies have the following attributes, for more info about Cookies
HTTP Only cookie
Secure Cookie

Securely store the "logged in" status of a user

I am using PHP and Codeigniter to do this. Currently I am just saving a cookie to the user with their username and a $logged_in variable set to true. Then when they try to access a page, I check for the status of their $logged_in, and if they are, they're free to access.
It occurs to me that this may not be the safest way to go about this. Is there a better tactic I should be using?
It's not safe at all. Cookie is considered user input and it can't be trusted in any case.
Use sessions instead.
Also you could use some sort of custom login encrypted code (I'd personally suggest SHA1) that is matched against the login code in the database and is refreshed every, let's say, 5 minutes.
CodeIgniter offers a nice solution to this problem - You can use Database Sessions.
With Database Sessions, all the data you put in a session is stored within your SQL database. The user gets a cookie with a unique session ID that changes on a regular basis. The session ID along with IP and User Agent is used to match up the user with their session data, thus making it impossible for users to tamper with their own session data, and very hard for them to hijack someone else's session.
You can read more about CodeIgniter Database Sessions in the CodeIgniter User Guide.

How to automatically re-login a user with a cookie

So on my application login form I've got one of those little boxes like [_]remember me
When the user checks that we set $_COOKIE['rememberMe'] with the value of the username. Now when that user comes back 3 days later, I obviously want to recognize them and re-log them in automatically. It doesn't sound safe to simply check for the existence of that cookie and then use it's value as the username to login without a password. But I'm not sure how else I would log them automatically... Is there a way this usually done?
Your cookie should have three values:
1. username
2. expiration time
3. a session code
When a user logs in, generate a session code and set an expiration time.
Store that session code and expiration time in the cookie and on your database.
Then whenever user returns to the site, and if user is not logged in:
1. check for the cookie
2. check for the cookie against the database
If all three variable matches and the expiration time is not over, log the user in.
Alternatively, if you simply encode the session code as say a md5 of ($username.$expiration_time), then you won't have to set up a database for storing and checking. Although having a database with randomly generated session code is much safer.
This is extremely unsafe. Since the cookie is the only thing you have to go by and the cookie is transferable from system to system, you would be vulnerable to cookie poisoning attacks and cookie copying attacks. If this is indeed the course you're set on, you will need to use some manner of foot-printing the user's system and storing that information in a database somewhere possibly as part of a persistent session on a session state server. This information could then be compared with the new login so if the cookie is transferred to a different system, it will not match and the automatic login will fail. As for accomplishing the login, I would recommend at a minimum to have a session state database where session information could be stored per session ID and username. If these 2 items are stored in the cookie, this information could then be used to get the information out of the database, and the foot-printing could be used as a stop-gap (although a very weak one) to prevent misuse.
The only information you need to store in a cookie is some unique hash that's going to point to the right user session in your system. Storing username or other information is redundant and unsafe considering the fact that username can be captured by an attacker and used with a combination of other information. To make the system more safe, you should implement a layer that'd check user's location by the IP address and his browser details. I suggest you should learn from what companies like Facebook and Google do with user accounts.
Place a random and uniqe hash in the cookie and store it in DB too with the current client's IP address.
If the user comes back, you can search for the hash in your DB.

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

Categories