473,403 Members | 2,323 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

sessions and cookies

pradeepjain
563 512MB
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
13 2628
Dormilich
8,658 Expert Mod 8TB
- session security.
Dec 20 '09 #2
pradeepjain
563 512MB
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
8,658 Expert Mod 8TB
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
563 512MB
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
563 512MB
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
8,658 Expert Mod 8TB
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
1,044 Expert 1GB
@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
8,658 Expert Mod 8TB
amazing, how two experts with completely different background criticize the same points…
Dec 22 '09 #9
kovik
1,044 Expert 1GB
Maybe it's a sign. :3
Dec 22 '09 #10
pradeepjain
563 512MB
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
1,044 Expert 1GB
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
563 512MB
i understood the session example, but cookies i did not get u :(. access keys -do u mean captcha?
Dec 23 '09 #13
kovik
1,044 Expert 1GB
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

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

Similar topics

1
by: windandwaves | last post by:
Hi Gurus I am basically sorry that I have to bother you about this. I am a PHP beginner and I have been studying sessions and cookies over the last few weeks. I have learned lots, but I am...
6
by: JJ | last post by:
Hi, I really need to use cookieless ASP sessions with ASP 3 (IIS5) Can I find out the session ID from the first page, then post it or send it with the url to the next page, then at the start...
2
by: | last post by:
Its strange...I have experimenting with browser hawk by using the cookie sniffer method. However, even If adjust the security slider level in internet options or goto advanced in the privacy tab I...
2
by: Steve Franks | last post by:
According to the docs you tell ASP.NET to use cookieless sessions by setting a value in the config.web file. However, what if I wanted to determine at run time whether or not I wanted to use...
2
by: Chris Mahoney | last post by:
Hi I'm using several Sessions in my app. When the user has cookies enabled in their browser, everything works fine. But with cookies disabled, only IE seems to remember the sessions. In Firefox...
7
by: Atte André Jensen | last post by:
Hi I'm developing a site where I'd like to store information during a users visit. So far I've been using sessions, but as far as I can tell it's not possible to control for how long a session...
6
by: Paul | last post by:
Here is a question that should get everyone going. I have an ecommerce site where I need to pass the order_id to every page. So which method is the best practice to pass this variable between...
13
Frinavale
by: Frinavale | last post by:
One of the most fundamental topics in web design is understanding how to pass information collected on one web page to another web page. There are many different ways you could do this: Cookies,...
5
by: jheines | last post by:
I am trying to explain how cookies and sessions work in a class I teach, but I have hit a wall when it comes to the interaction between cookies and the state of the privacy settings in Internet...
8
by: Chuck Anderson | last post by:
I've instituted a sessions based scheme on my web site to combat hot linking to my images. When someone requests a page at my site, I set a session variable. I then use htaccess to redirect *all*...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.