This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP session or cookie
We are developing a new project where we want to keep track of some information regarding the user from page to page, in terms of security, reliability and server usage is it better to do so with sessions or with cookies? What are the ups and downs of using one method or another.
For example to keep track if the user has successfully logged in or not, or to keep track of the language that the user selected.
Basically we want to know how to decide if we should use cookies or sessions, obviously if we want to keep track of data occurring within different visits to the page in different occasions and even different days the answer would be to use a cookie, but what about keeping track within the navigation of the page without closing the browser.
Thanks
A cookie is a small piece of text that is sent by the server to the client in the HTTP response headers. The client will store it locally and return it back to the server with every request in the request headers. That allows the implementation of some state in the otherwise stateless HTTP protocol.
A session is a concept typically implemented on top of cookies. The server sends a meaningless, unique session token (a random id) as a cookie to the client and the client returns it on every request. Server-side this id is associated with some data. Every time a client sends its session token back to the server in a request, the server looks up the data associated with that token.
The transfer of the session id back and forth between the client and the server can also happen by embedding the session id into all URLs or form requests, it doesn't have to be cookies. Embedding session ids in the URL is a bad idea though, since that allows accidental session transfers if URLs are shared between different users (see below). These days sessions are typically implemented using cookies client-side.
Conceptually cookies and sessions are extremely similar, they both implement state in HTTP. The difference is that a cookie can only store a small amount of data which is transferred back and forth on every request and is editable by the user (because it's information stored on the client); while a session stores all data server-side and is thereby only limited by the server's resources. The only vulnerability sessions have is that if a user can guess or steal the session id of another user, he can impersonate that user. That's known as session hijacking. Plain cookies have no security whatsoever and should not be used for anything important (as in, the user can see and edit the contents, so storing userloggedin=yes in a cookie is the worst thing you can do).
Related
I'm using session variable for login purpose. If login is successful $_SESSION['userName'] is set. In some pages there are codes like if(isset($_SESSION['userName'])) echo $_SESSION['userName];
I wonder if $_SESSION['userName'] is already set by other website in someone's browser it will lead to a huge problem. How may I overcome this problem, please suggest.
The session value is communicated between a browser and a server by HTTP cookie.
The HTTP cookie is only shared on the same host name like (*.stackoverflow.com)
So, I think another website cannot be get a session value of others.
So this is how a PHP session works.
PHP generates a session id for a specific user. It then hashes that ID and passes the hash to the user as a cookie.
On each subsequent request the user send that cookie back, PHP and looks up the session data for that session hash. It is then able to start the session associated with that user. In that sense no other user is able to access the first user's session without knowing the session hash.
However the end user is vulnerable to session hijacking in case someone else steals their cookies and there's a number of ways this can happen.
Session fixation which someone tricks a user of your site to use a session ID that someone has provided them (there's not much you can do about this).
Man in the middle attacks where someone is between the user and your website and intercepts all data that get passed along. This usually can be protected against by serving the page under HTTPS (not always but it's a lot harder for someone to steal data that comes over HTTPS).
Cross-site scripting (XSS), when someone uses client-side code (which can access cookies) to impersonate that user. You can protect against this by implementing CORS restrictions and sending a "nonce" with each response which you expect the user to return when they send the next request.
Taking advantage of browser exploits that expose the user's cookies to another website. It's normally a requirement to browser manufacturers to prevent websites from accessing cookies they did not set, but sometimes bugs can be present that prevent this. This is usually taken care of if the user keeps their browser up to date (not because exploits are not there but because most people haven't found them yet).
Someone breaks into a user's house and uses the user's browser (can't do anything about this one either).
There's probably more ways
What is the distinction between Sessions and Cookies in PHP?
A cookie is a bit of data stored by the browser and sent to the server with every request.
A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)
Cookies are used to identify sessions. Visit any site that is using cookies and pull up either Chrome inspect element and then network or FireBug if using Firefox.
You can see that there is a header sent to a server and also received called Cookie. Usually it contains some personal information (like an ID) that can be used on the server to identify a session. These cookies stay on your computer and your browser takes care of sending them to only the domains that are identified with it.
If there were no cookies then you would be sending a unique ID on every request via GET or POST. Cookies are like static id's that stay on your computer for some time.
A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session.save_path location and actually "see sessions". They are either files on the server filesystem or backed in a database.
The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.
Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.
Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.
Cookie
is a small amount of data saved in the browser (client-side)
can be set from PHP with setcookie and then will be sent to the client's browser (HTTP response header Set-cookie)
can be set directly client-side in Javascript: document.cookie = 'foo=bar';
if no expiration date is set, by default, it will expire when the browser is closed.
Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';. Close the tab, reopen the same website, open the Console, do document.cookie: you will see foo=bar is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie is empty.
you can also set a precise expiration date other than "deleted when browser is closed".
the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:
can be read client-side with document.cookie
can be read server-side with $_COOKIE['foo']
Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):
from bottle import get, run, request, response
#get('/')
def index():
if request.get_cookie("visited"):
return "Welcome back! Nice to see you again"
else:
response.set_cookie("visited", "yes")
return "Hello there! Nice to meet you"
run(host='localhost', port=8080, debug=True, reloader=True)
Session
is some data relative to a browser session saved server-side
each server-side language may implement it in a different way
in PHP, when session_start(); is called:
a random ID is generated by the server, e.g. jo96fme9ko0f85cdglb3hl6ah6
a file is saved on the server, containing the data: e.g. /var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/:
(it can also be be sent via the URL instead of cookie but not the default behaviour)
you can see the session ID on client-side with document.cookie:
the PHPSESSID cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.
can be set/read in PHP with $_SESSION
the client-side does not see the session data but only the ID: do this in index.php:
<?php
session_start();
$_SESSION["abc"]="def";
?>
The only thing that is seen on client-side is (as mentioned above) the session ID:
because of this, session is useful to store data that you don't want to be seen or modified by the client
you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie
A session is a chunk of data maintained at the server that maintains state between HTTP requests. HTTP is fundamentally a stateless protocol; sessions are used to give it statefulness.
A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.
Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.
Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.
Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.
One part missing in all these explanations is how are Cookies and Session linked- By SessionID cookie. Cookie goes back and forth between client and server - the server links the user (and its session) by session ID portion of the cookie.
You can send SessionID via url also (not the best best practice) - in case cookies are disabled by client.
Did I get this right?
Session
Session is used for maintaining a dialogue between server and user.
It is more secure because it is stored on the server, we cannot easily access it.
It embeds cookies on the user computer. It stores unlimited data.
Cookies
Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session.
It stores limited amount of data, and is maintained for a limited time.
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
This question already has an answer here:
What are cookies and sessions, and how do they relate to each other?
(1 answer)
Closed 5 years ago.
When i create a session variable where is saved username and password, how does it works internally? Same question about regular cookies where information is saved. Which type of information are included in coookie and session? What is the difference between them?
The best article on sessions and cookies I ever found is
http://shiflett.org/articles/the-truth-about-sessions
To sum it up a cookie is a file on the client's computer. You can store whatever in it (objects, text...). A session object can be stored in a cookie in the same way you can store some text. Keep in mind that session != cookie because sometimes you can store a session object in the database.
But still, you'll have to read up some documentation, I think.
Seen on wikipedia:
In computing, a cookie (also tracking
cookie, browser cookie, and HTTP
cookie) is a small piece of text
stored on a user's computer by a web
browser. A cookie consists of one or
more name-value pairs containing bits
of information such as user
preferences, shopping cart contents,
the identifier for a server-based
session, or other data used by
websites.
It is sent as an HTTP header by a web
server to a web browser and then sent
back unchanged by the browser each
time it accesses that server. A cookie
can be used for authenticating,
session tracking (state maintenance),
and remembering specific information
about users, such as site preferences
or the contents of their electronic
shopping carts. The term "cookie" is
derived from "magic cookie", a
well-known concept in UNIX computing
which inspired both the idea and the
name of browser cookies. Some
alternatives to cookies exist; each
has its own uses, advantages, and
drawbacks.
Being simple pieces of text, cookies
are not executable. They are neither
spyware or viruses, although cookies
from certain sites are detected by
many anti-spyware products because
they can allow users to be tracked
when they visit various sites.
Most modern browsers allow users to
decide whether to accept cookies, and
the time frame to keep them, but
rejecting cookies makes some websites
unusable. For example, shopping carts
or login systems implemented using
cookies do not work if cookies are
disabled.
Generally, session data is stored on the server, and it uses a tracking cookie to attach a user with the data. Cookies on the other hand are set directly in the user's browser.
One key difference: Session variables generally can't be seen by the end user, but cookies can(with the right browser plugin)
Also, if you have multiple front-end web servers, cookies will be sent to all front end servers, but session data is not shared between them without extra work.
I am interested in knowing how session management and cookies work in PHP. I want to know their underlying mechanism, like how the browser interacts with the cookies, and how the cookies are used to validate the session data in the server.
Is there any web resources that allow me to learn that?
In PHP in particular, the standard way sessions work is that PHP generates a random session ID, and puts it in a cookie. (By default called PHPSESSID) This cookie is handled by the browser by saving it locally on the user's machine, and is sent with every request to the domain it belongs to.
This session ID is then used to refer to a data store on the server machine, by standard located in /tmp/ on an apache install on linux. This is where everything in the $_SESSION array is stored between requests.
As you may notice, this is only as safe as the cookie is, as there is no real authentication between the user and server that the user is the "real" owner of the session ID. This means that so-called "session hijacking" is possible by sniffing the cookie and inserting the cookie with the session ID on the attacker's machine. This can be used to take over an account on a webpage, and browse around it just as if you were the original user, because to the server you are.
There's also an alternate, even more unsafe, way of keeping the session alive that PHP supports. This is done by sending the session ID as a GET variable with every link. As you may notice, this means that if a user simply copy-pastes one of these links, he will be giving away all his credentials. =)
Further information could be found in the PHP manual.
From PHP’s Session Handling manual:
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.
This unique id is a big random number that is stored on the server side to match it next time the client makes a new request. It typically goes into the /tmp directory.
A cookie is a bit of data that's associated with a HTTP address.
I.e.
1/ Browser requests www.google.com
2/ www.google.com response includes setting a cookie
3/ From this point on and as long as the cookie is valid (there's an expiry time associated with it), each subsequent request made by the browser to www.google.com/anything includes the cookie above
For details: http://en.wikipedia.org/wiki/HTTP_cookie
A cookie permits creating a session in the otherwise stateless HTTP protocol in the sense that it allows a client-server conversation to be isolated from other clients interacting with the server.