By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,971 Members | 1,467 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,971 IT Pros & Developers. It's quick & easy.

sessions and cookies

pradeepjain
100+
P: 563
hii guys ,
I am giving a presentation on sessions and cookies. i want to say points which are really worth telling . So i need some points about sessions and cookies which needs to be mentioned with out fail. some points on it.
Dec 19 '09 #1
Share this Question
Share on Google+
13 Replies


Dormilich
Expert Mod 5K+
P: 8,639
- session security.
Dec 20 '09 #2

pradeepjain
100+
P: 563
Hii..

i also wanna know some important topics on php on which i can give presentations on .
i am done with 1. security and 2. sessions and cookies
Dec 22 '09 #3

Dormilich
Expert Mod 5K+
P: 8,639
isn’t the purpose of your talk to work that out yourself? once you’re finished with its concept, we can have a look, whether we see something important missing.
Dec 22 '09 #4

pradeepjain
100+
P: 563
yeah i know...if i get some topic names ..i will work on it !!t tot like that!!:)

yeah i tried to upload the file which i created but the size is getting bigger !!!
Dec 22 '09 #5

pradeepjain
100+
P: 563
This is the presentation i have prepared . hope its good enough to post it over here.


Sessions and Cookies


Why do we need sessions/cookies ?

HTTP is a stateless protocol. This means that each request is handled independently of all the other requests and it means that a server or a script cannot remember if a user has been there before. However, knowing if a user has been there before is often required and therefore something known as cookies and sessions have been implemented in order to cope with that problem.

What is a cookie ?

Here are some of the features of a cookie:
Stored on the client computer and are thus decentralized.
Can be set to a long lifespan and/or set to expire after a period of time from seconds to years.
They work well with large sites that may use several webservers.
Won’t do you any good if the client has set their browser to disable cookies.
Limitations on size and number: a browser can keep only the last 20 cookies sent from a particular domain, and the values that a cookie can hold are limited to 4 KB in size.
Can be edited beyond your control since they reside on the client system.


Note: The setcookie() function must appear BEFORE the <html> tag.
Because the setcookie() function is sending headers, it is important that you call this function before any content has been output to the browser. Headers are always at the top of an HTTP response, so once you start outputting content you will not be able to send any more headers.

Syntax :

setcookie(name, value, expire, path, domain,secure,httponly);

Expire : This is expressed with a Unix timestamp. You will have to set the date and time of when the cookie should expire. You will not be able to make a cookie that lasts "forever", but you can make the cookie last a long time (several years for instance). If you want to set a cookie that lasts 30 days, then you could get the timestamp like this:
$expire = time() + 60 * 60 * 24 * 30; // or 2592000
// ... or ...
$expire = strtotime('+30 days');
The fourth parameter, path, is used to control which scripts that can access the cookie. This is relative to the document root. Say for instance you have http://example.com/forums/index.php and you want to set a cookie using that file. If you set the path to /forums, then the cookie will only be accessible to scripts within the /forums path. If you leave it blank then there is no restriction.

The fifth paramter, domain, works much like path does. However, this time the restriction is which domains that can access the cookie. If we say that you both have www.example.com and forums.example.com then setting $domain to forums.example.com will mean that the cookie is only accessible from the forums subdomain. You can also set it to .example.com and then all subdomains for example.com (e.g. www and forums) will be able to access it.

If you are using a free host where your domain name will be a subdomain of the host's domain (e.g. mysite.awesome-host.biz or something like that) then you might want to ensure that only your specific subdomain will be able to access your cookies so all the other users won't eat them.

Secure : Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection

httponly : When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks

Cookie Example :

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $visits = intval($_COOKIE['visits']);
  3. setcookie('visits', $visits + 1, strtotime('+30 days'));
  4. if ($visits == 0) {
  5. echo 'I have never seen you before, but I am glad you are here :)';
  6. }
  7. else {
  8.  echo 'Welcome back! You have been here ', $visits, ' time(s) before';
  9. }
  10. ?>

What are session ?
Sessions, according to PHP.net, are "a way to preserve certain data across subsequent accesses”
In the background processes on the server, PHP runs a garbage collecting process that destroys all sessions that have been inactive for twenty-four minutes .
Here are some features of sessions :
Server-size cookie can store very large amounts of data while regular cookies are limited in size.
Since the client-side cookie generated by a session only contains the id reference (a random string of 32 hexadecimal digits, such as ‘fca17f071bbg9bf7f85ca281653499a4′ called a ’session id’) .
Much more secure than regular cookies since the data is stored on the server and cannot be edited by the user.
Only last until the user closes their browser.
Won’t work if client has cookies disabled in their browser.
Can be easily customized to store the information created in the session to a database.
Information is available in your code as soon as it is set.
Expand|Select|Wrap|Line Numbers
  1. <?php echo "http://www.yoursite.com/yourphppage.php?PHPSESSID=" . session_id();" ?>
  2. Then use the following in the loading page to retrieve the session id:
  3. <?php echo $_GET[‘PHPSESSID’]; ?>
Session support in PHP consists of a way to preserve certain data across subsequent accesses .i.e where your website need to pass along user data from one page to another, it might be time to start thinking about using PHP sessions.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc). However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.

The way sessions work are by generating a random ID for the user. This ID is stored in a cookie on the client machine. PHP will then fetch all session data related to that ID from wherever it is stored. By default it's stored on the harddisk, but it's possible to write your own save handler so you can store it in e.g. a database. By default, the cookie will be called PHPSESSID and will expire when the browser is closed.

Seeing as you are using a cookie for identifying the user you'll need a way to set the same settings for the cookie as we did before. For this purpose you can use the session_set_cookie_params() function. It has the following syntax:
session_set_cookie_params(int $lifetime[, string $path[, string $domain[, bool $secure[, bool $httponly]]]])
Before you are able to use sessions you'll have to call session_start(). This function will, like when setting cookies, have to be called before any output has been sent to the browser. Once this has been done, storing data in sessions and retrieving the values is quite easy:

Session Example

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3. $visits = $_SESSION['visits']++;
  4. if ($visits == 0) {
  5. echo 'I have never seen you before, but I am glad you are here :)';
  6. }
  7. else {
  8. echo 'Welcome back! You have been here ', $visits, ' time(s) before';
  9. }
  10. ?>
Sessions without cookies
Sessions do not always have to use cookies. Whatever value you choose for the session name (PHPSESSID by default) just have to be present somewhere. It could for instance be through the URL like this: http://example.com/index.php?PHPSESS...87Hajhsd97Hash or it could be through a form field (either via POST or GET).

Cookies vs. Sessions
Both cookies and sessions are available to you as a PHP developer, and both accomplish much the same task of storing data across pages on your site. However, there are differences between the two that will make each favourable in their own circumstance.
Cookies can be set to a long lifespan, which means that data stored in a cookie can be stored for months if not years. Cookies, having their data stored on the client, work smoothly when you have a cluster of web servers, whereas sessions are stored on the server, meaning in one of your web servers handles the first request, the other web servers in your cluster will not have the stored information.
Sessions are stored on the server, which means clients do not have access to the information you store about them - this is particularly important if you store shopping baskets or other information you do not want you visitors to be able to edit by hand by hacking their cookies. Session data, being stored on your server, does not need to be transmitted with each page; clients just need to send an ID and the data is loaded from the local file. Finally, sessions can be any size you want because they are held on your server, whereas many web browsers have a limit on how big cookies can be to stop rogue web sites chewing up gigabytes of data with meaningless cookie information.
So, as you can see, each have their own advantages, but at the end of the day it usually comes down one choice: do you want your data to work when you visitor comes back the next day? If so, then your only choice is cookies - if you have any particularly sensitive information, your best bet is to store it in a database, then use the cookie to store an ID number to reference the data. If you do not need semi-permanent data, then sessions are generally preferred, as they are a little easier to use, do not require their data to be sent in entirety with each page, and are also cleaned up as soon as your visitor closes their web browser.
Choosing the appropriate option

In its default implementation (as above), you should not use sessions in very large projects which are likely to be deployed on multiple load-balancing servers. The reason behind this may not be apparent at first, but if you recall, session data is actually stored in a file on a server's computer. If a user visits your site, and your load-balancer redirects them to one server for a request, that server has their session data. Next time they read a page, your load-balancer may well shift them to another server, leaving their original session data on the original server. The second server might also save some session data of its own.
Security issues
Because the cookies are transferred unencrypted (unless you are using SSL) and because they will be stored in plaintext on the client computer, it is not advised that you store any sensitive information in the cookies. Such information could, for instance, be the username and/or password. For purposes such as authentication it would be best to store a unique identifier in a cookie and store the rest of the information on the server. In that way it never leaves the server and therefore it is stored in a safe manner (providing your server is secure). Seeing as sessions do this, they would be a better choice for that purpose.
An instance where you would not want to use sessions instead of cookies would be if you need Javascript or another client-side scripting language to access the information. Seeing as session data is stored on the server, there is no way whatsoever it can be access from the client machine. Again, this information should not be sensitive.
A problem related to this is a security issue known as XSS (Cross Site Scripting). This vulnerability exists if users are able to post information (via a form or the URL for instance) and that information is redisplayed on a page without being properly escaped. In that way a malicious user will be able to execute any arbitrary Javascript code on the client machine without the user or you knowing it. The reason why this is a problem regarding cookie and session security is that cookies will be default be able to be viewed by Javascript. There are a number of different ways you could deal with this. The first and most obvious one is to properly escape all output coming from a user. The function htmlentities() can take care of that. Another way is by setting the httponly parameter for your cookies. In that way the browser will not give Javascript access to the information that cookie holds. If you are using sessions, then you can call session_regenerate_id() on every request. By doing that the user will get a new session ID each time and it means that if a malicious user ever gets a session id, chances are it will be invalid by the time he gets to try it because it changes often. Stealing the session IDs and attempting to use them is known as session fixation.


However, sessions present a few advantages and disadvantages. For instance, every time a PHP script accesses (values do not necessarily have to be changed) a session, the garbage collector resets its twenty-four minute countdown for deletion. Thus, a user cannot leave a site and come back in an hour or two and expect the session to still be alive. In addition, a user's computer deletes all session IDs every time the user closes the browser. Thus, the only real advantage of using sessions is that they allow a PHP programmer to hide what information is being stored from the users and hackers. However, hackers can hijack sessions with a cookie grabber, so one cannot argue that sessions are much more secure than cookies. The only security advantage of sessions is that they hide information; thus, if a website stored a user's (encrypted) password in a cookie and a hacker somehow obtained the cookie, the hacker could run a password cracker on the encrypted password to decipher it, whereas a session hijacker would have only have access to the account, not the encrypted password. PHP programmers should use sessions only for things that require the short-term preservation of data, such as a CAPTCHA script or a shopping cart. PHP programmers should not use sessions for things such that require the long-term preservation of data, such as login pages or user preferences. Overall, sessions serve as a short-term method for preserving data across pages while hiding information from users and hackers.

Cookies are the conventional alternative to sessions: they have been around for what seems like forever, and they are not specific to PHP. PHP.net defines them as "a mechanism for storing data in the remote browser and thus tracking or identifying return users." Cookies last a set interval of time—even if the user closes the browser (unless of course he clears his cookies)—and then they expire. The only disadvantage to using a cookie is that the information is stored locally on the user's computer in a text file. Therefore, hackers who use cookie stealers can access the information as well as anyone with physical or remote access to the computer's files; this can be a security threat. However, a well-coded website prevents cookie grabbers from working, and thus eliminates most of the security threat. However, it is important to keep in mind that users can easily change the value of a cookie, so treat anything inside of a cookie as malicious user input. Therefore, PHP programmers should use cookies as a long-term solution to preserve data across pages and sessions.
Overall, sessions serve as temporary information holder that can hide information, whereas cookies serve as both a temporary and long-term information holder. After the difference between sessions and cookies is apparent, making the right choice for a website is rather simple. Though sessions may seem easier to use than cookies, never doubt the power and ease of using cookies.
Dec 22 '09 #6

Dormilich
Expert Mod 5K+
P: 8,639
neat talk… though there are some points, which are not entirely correct.

you should definitely mention, that sessions have a Runtime Configuration.

Can be set to a long lifespan and/or set to expire after a period of time from seconds to years.
they can also be set to be deleted, if the browser is closed.

you should at least write down (if only for personal use) the structure/complete options of a cookie (wikipedia has a good overview, there should also be a RFC somewhere)

Server-size cookie can store very large amounts…
I wouldn’t go as far as calling a session a ‘server-size cookie’.

Only last until the user closes their browser.
wrong. sessions last as long, as they are not deleted by the garbage collector.

Won’t work if client has cookies disabled in their browser.
wrong. if cookies are disabled, the session id is written in the elements specified by url_rewriter.tags. you can also use sessions explicitly without cookies (session.use_cookies = 0)

Information is available in your code as soon as it is set.
the following code box has nothing to do with sessions. and PHP strings are delimited by either ' or ", not any of the typographical quotation marks.

Expand|Select|Wrap|Line Numbers
  1. $visits = $_SESSION['visits']++;
I doubt this will ever give 0, except when being set to –1 beforehand. (and always check that a value/key exists before reading it)

However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.
that depends on te settings of the Garbage Collector.

This ID is stored in a cookie on the client machine.
mind that this is only the default setting.

do you want your data to work when you visitor comes back the next day? If so, then your only choice is cookies
this is not entirely correct. although it doesn’t make sense to make long-living sessions. I’d rather recommend cookies for that, than excluding sessions.

If you do not need semi-permanent data, then sessions are generally preferred, as they are a little easier to use, do not require their data to be sent in entirety with each page, and are also cleaned up as soon as your visitor closes their web browser.
sessions do not transfer their data at all. thus they can’t be cleaned up on browser closing. you should rephrase that sentence, because it can be misleading.

In its default implementation (as above), you should not use sessions in very large projects which are likely to be deployed on multiple load-balancing servers.
this (and the following paragraph) sounds as if it were impossible at all. if you store session information in a database, it should work also across servers. I’d rather tell it the other way round: “if you have a project with several servers, you can’t use the default configuration. storing the data in a database can solve this.” (through session_set_save_handler())

An instance where you would not want to use sessions instead of cookies would be if you need Javascript or another client-side scripting language to access the information. Seeing as session data is stored on the server, there is no way whatsoever it can be access from the client machine.
wrong. make an AJAX call using the transmitted session id. more complex, but possible.

The reason why this is a problem regarding cookie and session security is that cookies will be default be able to be viewed by Javascript. There are a number of different ways you could deal with this. The first and most obvious one is to properly escape all output coming from a user.
the first and most obvious one is setting session.cookie_httponly to true* (like you tell in the next sentence). although user input must be validated (escaping is not secure enough) anytime, anywhere.

* escaping does not prevent the exploitation of the cookie being readable by scripts, thus not being the first and most obvious (which would be blocking the cookie to the script)

For instance, every time a PHP script accesses a session, the garbage collector resets its twenty-four minute countdown for deletion.
only if you are using the defaults. in fact, Garbage Collection is not as simple as you present it here. in theory, session data can persist much longer that the lifetime suggests.

Thus, a user cannot leave a site and come back in an hour or two and expect the session to still be alive. … In addition, a user's computer deletes all session IDs every time the user closes the browser.
wrong. with the right settings for the garbage collector and the session cookie/parameter he can. definitely. session cookies are only deleted when they expire, this is not necessarily the closing of the browser.

Thus, the only real advantage of using sessions is …
you list further advantages during that paragraph… I’d rather tell the facts in a neutral style.

PHP programmers should not use sessions for things such that require the long-term preservation of data, such as login pages or user preferences.
what about databases? if you clean your cookies (e.g. by accident), the ‘long-term’ info is gone with the wind.

Therefore, PHP programmers should use cookies as a long-term solution to preserve data across pages and sessions.
I cannot agree with that.


overall, I got the impression, that you are a bit preoccupied about sessions (in favour of cookies). I recommend to rephrase especially the last paragraphs to a more neutral style, so as to present the listener a more balanced report.
Dec 22 '09 #7

kovik
Expert 100+
P: 1,044
@pradeepjain
It'd be nice if you used isset($_COOKIE['visits']) before parsing it to a value. When it is unset, it will throw a warning in PHP.

@pradeepjain
By default. All defaults in PHP are changeable. There are a lot of settings for session that can be altered via ini_set(). These settings all all of the session.* settings.

@pradeepjain
The $_COOKIE array isn't the only valid location of the session ID. It can also be in the $_GET array, and PHP alway checks the $_GET array when the session ID isn't found in the $_COOKIE array. The global constant "SID" includes a session name and ID pair in the format "{name}={id}" for easy appending to URLs, and it only exists when the cookie has not yet been created or will not be able to be created. So, you can safely append it to every URL, and it won't exist after the cookie is created.

@pradeepjain
It shouldn't be. Session data usually remains long after the user has left. Whether or not their session cookie still exists is dependent on their browser. Without it, that particular user will not be able to access their old session, but it still exists. If they new the session ID, they could re-create the cookie and regain access (part of why security is an issue with sessions).


@pradeepjain
... Why do you have this section? Sessions are basically giving the user an "access code" (similar to a username/password combination) to data stored on the server. We put this access code into the cookie to make it a little harder for hackers or eavesdroppers to access it. Cookies are not secure, however, and a session is only as secure as the means it takes to access it (just like a user account is only as secure as its password). Comparing cookies and sessions makes very little sense, to me. They have different purposes.

Sessions are server-side. Cookies are client-side. Comparison done? :P


@pradeepjain
You should at least state that using the database instead of the file system can solve this problem.

@pradeepjain
That is certainly overkill. The disadvantage of this is that using multiple session IDs per session increases the chance of session ID collision. Example: One user has a session ID stored in their session cookie. Their session ends server-side, but their client-side cookie still exists. Another user's ID turns into their old ID, and they refresh their browser. They now have access to the other user's session, and completely by accident. They'll be confused and do something irreversible to the account in question before realizing. Now you have a confused user and a surprised user. Good job. :P


@pradeepjain
The GC isn't guaranteed to run. I've had times when my GC didn't run for almost a day.

@pradeepjain
This is vague. Are you saying that this information should be permanently stored in the database and not in a session? If so.. Why would you even say that? o.O You already stated many times that sessions are temporary.

@pradeepjain
Cookies are not an alternative... They serve a different purpose. And sessions are not specific to PHP... PHP is one of the newest web programming languages. They didn't invent sessions. :P


All in all, I feel that you have at least touched on everything that I have said, but in a VERY unorderly fashion. For most of the comments that I made, I'd see that much later, you'd mention something in regards to it. Your presentation is very mislead in certain parts and could use more organization.
Dec 22 '09 #8

Dormilich
Expert Mod 5K+
P: 8,639
amazing, how two experts with completely different background criticize the same points…
Dec 22 '09 #9

kovik
Expert 100+
P: 1,044
Maybe it's a sign. :3
Dec 22 '09 #10

pradeepjain
100+
P: 563
thanks a lot for taking time and correcting me!!!


I need 1 small help !!! i need 1 very gud examples for of where sessions and cookies are used !!so that while explaining i will give a correct picture to them !

and i willl reorder the talk and remove the misleading points and post it back!:)
Dec 22 '09 #11

kovik
Expert 100+
P: 1,044
Sessions are used to store the current logged in user's information for authentication against the database. Cookies can be used to enable a user to be automatically logged in with an "access key," which would be regenerated every time that they log in.
Dec 22 '09 #12

pradeepjain
100+
P: 563
i understood the session example, but cookies i did not get u :(. access keys -do u mean captcha?
Dec 23 '09 #13

kovik
Expert 100+
P: 1,044
No... What is with your obsession with CAPTCHAs? o.O

An "access key" is like a username-password combination. However, for an auto-login, you want to generate a random string that will serve as the user's access key. This key is saved both in the database and the cookie. Then, when the user accesses the site and does not have an active session, you check this cookie against the database. If it is a valid access key, you proceed as if the user has logged in regularly. Then, you generate a new access key and save it.

It's a technique utilized by systems with an auto-login subsystem such as Facebook, Google, and phpBB.
Dec 23 '09 #14

Post your reply

Sign in to post your reply or Sign up for a free account.