Cookie and session in "remember me" feature - php

I have never wanted to allow a user to stay logged in for any length of time so I never saw a use for a "remember me" feature. I started thinking about how it's done though and would like some clarification.
I'm currently storing my sessions in a database. What has always perplexed me was how, even though I do not explicitly set a cookie, one is placed in my browser. I'm a little confused because a session is a session and a cookie is a cookie. I don't see how a session sets a cookie.
I'd also like to know if, simply setting another session variable in the session array to keep the user logged in, would be sufficient or would I still need to set a cookie?

In order to pull the session data back from your database a key is needed. This is called the Session ID.
The session ID needs to be stored somewhere. Either as part of the URL string that the client posts back or, more commonly, in a cookie on the client. When the request is posted, session reads the value from the cookie and knows which record to pull back from session storage.
This happens automatically.
The only reason to use session is if the data you want to keep is greater than 4KB (browser limitations); or if the time required to pull the data from your server is greater than reading it from session storage.
If the amount of data you are storing is less than 4KB I would highly recommend you just set that in the cookie to begin with. I generally store things like the user id, user first name, and a couple other attributes. Bear in mind that it is trivial to inspect a cookies value, so this information should be encrypted prior to going to the client.
Another thing is if the query time to pull the data you need from the original source is small, then elect to do that instead of placing it in session. That way you only get it when you actually need it instead of with every single page load.

What has always perplexed me was how, even though I do not explicitly set a cookie, one is placed in my browser.
A session handler has to identify which session belongs to which user.
The vast majority of session libraries do this by setting a cookie.
(Is) setting another session variable in the session array to keep the user logged in would be sufficient or would I still need to set a cookie?
Most session libraries set session cookies. These are cookies without a specified expiry time. They expire when the browser closes and are not sufficient to implement a "Remember Me" feature (which is expected to persist across browser restarts, so must have an explicit expiry time).

Explaining the relationship between Cookie and Session:
PHP uses Cookie to uniquely identify the session for each user. That's the only more reliable way because cookie is sent each time you request a file from the server. Using the token in the cookie, which is also the Session identifier, PHP will look up the tmp directory to see if the session exists. If the session exists, the variables are loaded from the correct file and you will be able to access the variables on that session.
Therefore, cookies store the session identifier which is required to identify which user uses which session. This is also how Session Hijacking come about, when people can change the session identifying cookie to use another person's session identifier.

The underlying PHP session implementation sets the cookie. You can alter this and have the session ID value passed in the query string, but I don't recommend it. You don't use the cookie, PHP does. It references the session ID value stored in the cookie to perform lookups to session data.
I'd also like to know, if simply setting another session variable in the session array to keep the user logged in would be sufficient or would I still need to set a cookie?
As soon as the user closes the browser, the session is killed and the cookie is deleted. I don't believe any mechanism exits to persist the session value, and for good reason.

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.

Managing multiple users in php

I am a newbie to php.
I just learned that you can create a session variable for a user after his login such as
$_SESSION['id']=****some value(say 3)******;
and this session variable is maintained as long as he doesn't log out(i.e. you clear this session variable using session_destroy).
Now , I have a confusion that if another user logs in then won't this id variable be overwritten thus logging the previous user out?
If this is true ,then what can I do to resolve it?
PHP sessions are tied to a user by a unique (random) ID string, generated the first time you invoke session_start() for a user. That ID is stored in the client browser as a cookie (or possibly via hidden form fields/query parameters).
Even though $_SESSION is used throughout the code, the CONTENTS of that $_SESSION array are tied to a particular user via that ID string. That means if I hit your site, $_SESSION will contain my details. If you hit your site, $_SESSION will contain your details.
There should be no practical way for my details to "leak" in your session, or vice versa. Destroying my session will not destroy yours, because yours is a completely different session, with a different ID.
All sessions are tied to a unique session ID. This is typically set inside the user's cookie.

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.

What is difference between session and cookie in php?

Hi I would like to know the difference between a php session and a cookie
The main difference being that session data is stored on the server, while cookie data is stored on the client. Therefore, a client can easily modify the cookie contents, but will have to work way harder to modify the session contents.
Cookies are a means to store information in the end-user's browser, so that the server can track the end-user.
Sessions are also implemented by using cookies, but the actual data is not in the browser; rather, it is stored in the user's session record on the server. In the case of sessions, cookies are used to identify a particular end-user's session identifier on the server records. Hence, they are a more secure way of storing user information.
A cookie is a ~piece of data stored on the client side.
Data stored in session is stored on the server side, and the various sessions are identified by cookies.
There are session and Cookies, both are used to store values or data. But there are some key differences between session and cookie: a cookie stores the data in your browser and a session is stored on the server. Cookie data is available in your browser up to expiration date and session data available for the browser run, after closing the browser we will lose the session information.
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.
A session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
A cookie is an unique information that the user sends to the web server with each request in order to identify him. This unique id could be used to store information about this specific user on the server (session).
Cookies will only expire on expiry time or if you explicitly clean cookie / cache of your browser. Cookies will retain into the system even after you open your browser next day.
Cookies are stored on client's system so they are less secure.
Session will expire on its expiry time or if the browser has been closed. As session is stored on server so it is more secure.
So for a login module, a combination of session and cookie should be used
Cookies stored client side but session stored server side.
cookies is without sign out of the your email account and close it. once again can not enter username and password but your email account is open.
session is close the webpage once again open to starting page appier
best example to illustrate the difference bet. Session and Cookies is:-
when you Login as a member in any Site it Creates Sessions until you log out...
that is Session..
and Cookies when you browse websites the are stored on your computer's Main Memory that is Cookies
i-e Session is Server side
and cookies is Client side
We got three differences in general. The key difference would be cookies are stored in client side and sessions are stored in server side. The second difference would be cookies can only store strings. We can store our objects in sessions. Storing objects in sessions were really useful according to my experience. Another difference was that we could be save cookie for future reference, but session couldn’t. When users close their browser, they also lost the session.
PHP Sessions
PHP has built-in functions to save session variables. The variables are stored in state files. These state files need not be explicitly created and managed. The following are the steps for saving and retrieving values of session variables.
The setcookie() command must be issued before any printed output occurs because the cookie must be written as part of the HTTP header. PHP automatically parses any HTTP_COOKIE string into an associative array $_COOKIE. The value of the cookie can be retrieved from the cookie thus:
$_COOKIE["some_var"]
Cookie: A key/value pair that is stored by the user's browser and is available in the superglobal $_COOKIE array available in PHP. The cookie request is initiated with an explicitly defined expiration date. For example:
setcookie('cookieName', $some_value, time()+3600, "/", ".example.com")
On the next server request, $_COOKIE['cookieName'] will be available. If you use a browser tool to look at the cookie, it will have an expiration date.
Session Cookie: Identical to the above but defined without an expiration date. If you use the same browser tool it will say that the cookie expires at the end of the session; which is ultimately when you close your browser. For example:
setcookie('cookieName', $some_value);
PHP Session: a server side mechanism that will associate a bunch of data with a session id. Every time a session is invoked, it serializes/unserializes it. This could be more data than just a single key/value pair that a cookie supports, but the way of associating this data with a user is by creating a cookie (regular or session as described above) in their browser that contains the session id. This way, the right data can be retrieved for a given user based on the value of that cookie.
Both are super global, i.e, they can be used anywhere in the site.
Differences between sessions and cookies:
Cookies are stored in the browser (client side) while sessions are stored in the server (host).
Cookies are remembered till they are deleted while sessions are deleted when the user closes the tab/browser (depending on the browser).
Cookies can be seen by the user while sessions cannot.
Due to the reasons above, I would recommend to not store sensitive data in cookies and store the data that is to be remembered even after the user has left in cookies.
Cookie - Stored data in browser and will work on browser related and client side only...For example if you are trying to log in gmail account with username and password,After entered login successful if you close the current tab and after sometime opening same page the login page won't come it will open directly with login details..This is cookie..
Session - Stored data in server side for example same as cookie example after entered login details you will get notification as successful once you close the browser then open after some time it will ask again login details(more example shopping also)

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