How session and cookie works? [duplicate] - php

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.

Related

PHP session VS PHP cookie [duplicate]

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).

PHP Session Hijacking

I have a question regarding session hijacking in PHP. I have been reading about it this morning and I have a few questions that just weren't answered clearly in the documentation I read.
Can a user change their session on my website? i.e. if they have a session of X when the login, can they change that session to Y, or Z, if they so choose?
I thought that sessions were set by the browser and they couldn't be changed, but all of this session hijacking stuff I've been reading has put some doubt in my mind.
The term "session" is overloaded to mean different things on the server and in the browser. Browser sessions are at best tenuously connected to server sessions. "Session hijacking" refers to server sessions.
Server-side, a session has an ID (which is passed between the client and server), content (stored on the server) and potentially other properties, such as last access time. The session ID is usually passed as a cookie. In PHP the default name for the cookie is "PHPSESSID". If cookies aren't available, PHP will (optionally) use a query string parameter of the same name ("PHPSESSID"). This cookie (or query param) can easily be changed and therefore the session identifier can be changed too.
The contents of a session (i.e. containing the login state of a user) cannot be changed by the client, the data is stored on the server and can only be changed by a PHP script on that server. Note that in a shared-hosting environment (shared by other services or users), the sessions can be overwritten if using the default session storage directory (/tmp). To protect against that, either use a database through session_set_save_handler() or set a custom session directory using session.save_path with the proper directory permissions set (preferably 700 which means that only the owner (the PHP user) can read and write to it).
To protect against session hijacking, you must have other ways to identify the user against a session. This can be a user agent, IP address or another cookie. The previously mentioned methods are just workarounds, best way to protect against stealing of the session cookie is by using HTTPS if a session is involved. Do not forget to set the httponly flag to true using session_set_cookie_params()
Client-side, "session" is again overloaded and used in various contexts (e.g. session managers, which restore open pages when a browser is opened, session cookies and sessionStorage). We can try to combine these meanings (into what is by no means a standard one) by saying a browser session consists of a collection of views and their associated data. (By "view" I mean roughly tabs in tabbed browsers and windows in non-tabbed browsers; the DOM window object exposes a view to JS.) Each view has a history, a current page and page data. Page data for pages in the same domain is shared between views in a session; if two pages are in different domains or different sessions, they don't share data. Exiting the browser closes all open session(s), possibly saving part of the session(s) (e.g. histories, current pages, sessionStorage) so that a session manager can re-open them. Session cookies are cookies that are discarded when a session is closed; in other words, session cookies are non-persistant. Though a session cookie may hold a session ID, the two concepts are orthogonal (sense 4; session cookies can hold things other than session IDs, and session IDs can be stored in persistant cookies).
Whether two different views are in the same collection depends on the browser. For example, one browser may consider a session to consist of all tabs within a single window; separate windows are separate sessions. IE8 lets users create new sessions via the "New session" menu item. Otherwise, new windows and tabs are opened in the same session. Privacy modes also create new sessions.
In summary, browser sessions are indeed set by the browser, though it provides users various means of controlling browser sessions: creating new sessions, changing the history and current page in a view by browsing, saving and restoring sessions. A user could even change session data by editing sessions saved on disk, though this isn't a feature afforded by the browser. None of this has anything to do with session hijacking. Server sessions are created and managed by the server, but users can (attempt to) switch server sessions by changing the session ID their browser passes back to the server, which is the basis for session hijacking.
See also PHP Session Fixation / Hijacking.
A user can change his session at any time. It's just a random string stored in a cookie in the users browser, and therefore it is very simple for the user to change it.
As the actual content of the session is stored on your server, you could for instance store the user's ip address, user agent or similar to make it harder to steal sessions from each other, by checking if this information still matches each time a new http request is made.
No actually user can not change the actual session value at your website but can change the session id that is used to track the session this session id is stored on client browser by your website usually name "PHPSESSID" in cookie which are also known as session cookie. When a session is started on a site it stores the unique id corresponding to that session in the respective client browser in form of cookie named as "PHPSESSID". So if user is able to get PHPSESSID of any other user and it can replace his PHPSESSID with the victims PHPSESSID and it will result in session hijacking.
I am using PHP context here.

PHP sessions and cookies question

Is PHP sessions the same as cookies? I ask this because I'm writing a privacy policy and the site uses PHP sessions, MySQL, JQuery and CSS. If Session are not the same should I change or leave the cookies name?
Here is what I have so far.
Cookies - The Website uses "cookies," a technology that stores a small amount of information on a user's computer to permit the Website to recognize future visits using that computer. Cookies enhance the convenience and use of the Website. For example, the information provided through cookies is used to recognize you as a previous user of the Website (so you do not have to enter your personal information every time), offer personalized content and information for your use and otherwise facilitate your Website experience.
PHP sessions are stored, by default, in a temp directory on the webserver. The session id is stored in a cookie called PHPSESSID. By default, these are not tracking cookies and don't have to be persistent (e.g. they expire whenever you close your browser). So they are safe to use even in websites that have enforced privacy regs.
For instance, I worked for a major branch of the U.S. military and we used _SESSION's all the time, despite the U.S. government forbidding a great many types of cookies.
To make a session cookie non-persistent:
// Make the session cookie last for 24 hours.
ini_set('session.cookie_lifetime', 86400);
Sessions are stored in the server, and after an previusly set ammount of time, it dies, or in other words, its deleted. Sessions do not need permission from the user to create, as a matter of fact, php initializes a session for each new web request that arrives from an ip to the server.
Cookies, on the other hand, are data stored in the browser's data folder, and every user needs to authorize the site to use them, and of course, they are not shared, meaning that IE and Firefox cannot share a cookie.
An example would be to login in this site and next time you point your browser it will remember your credentials, but if you try to open it with IE, it won't know who you are, hence the fact that they don't share data.
Hope it helps
Best of luck!

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

Session Management and cookies-- the interaction mechanism

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.

Categories