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.
Related
I am building a website and I am using sessions to check user login. I am wondering if there is any better and safer way to check user login. Because sessions are stored in the clients computer I think they are not very safe and easy to hack. Am I correct?How do big websites like facebook and twitter check if their user is logged in or not. I am new to PHP so dont say my question is too basic.
Sessions are not stored in the client's computer. You must be confused with cookies !
Sessions are definitely the way to go here.
No matter what you use as authentication, if the client computer is compromised, the client's method of authentication can be abused. So in this regard, any other way can only be as safe as sessions are.
All big sites use sessions, usually in conjunction with cookies.
I want you to first understand that Sessions are the only way you can identify a client.
You don't store sessions on either the client or server side. (If you want a secure system.)
First you need to understand the need for sessions, only then you can know what sessions are.
The internet is a stateless network of machines, each with their own identifiers. Most of the communication that we do while sending a request to load a page or visit various links are over the HTTP (Hyper Text Transfer Protocol).
HTTP is a stateless protocol, meaning any communication over this protocol is not required by the protocol to be stored on either the server or client.
Let us understand what this would mean, with an example:
Suppose you try to login to http://example.com
You fill the form, hit the send button.
All the data in your form is then sent to the server.
The server checks if the username and password received was right. If right, it sends you the secure data.
In your next call to the web server, you expect to be logged in. BUT, due to the stateless nature of HTTP, your server does not recognize you anymore.
You can make this work by sending your username and password with every call, but that would mean having to enter it every-time for each request.
Here comes the role of cookies, you set the username cookie as Joe and password cookie as qwerty. Now everytime a request is sent the cookies are sent by the browser and you are happy.
This scenario now again has a problem that you need to make an authentication check everytime on your server thus increasing the load on it.
Enter Sessions. Sessions mean states with some context. It may be a logged in user, it may contain preferences you have set or any other similar stuff.
Here, when the user is logged in the first time, the server generates a session ID. This session ID is then stored by the server in a DB, File or it's Memory (RAM) along with any other data like username of the person who is logged in, preferences etc.
The server response then contains the session ID, which may be in the form of a cookie, HTML5 session states or sometimes even hidden fields.
Now, every call the client makes, contains the session ID. The server then checks its session store for any valid sessions with the same ID and get into context therby giving a pseudo state-like mechanism to communications taking place over HTTP.
How long your browser stores this cookie can also be determined by the server while sending the cookie.
There are advanced techniques for further security like changing the session ID each time a call is made, but lets get into that only if you want me to.
Cheers! :)
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).
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.
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