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 :
- <?php
-
$visits = intval($_COOKIE['visits']);
-
setcookie('visits', $visits + 1, strtotime('+30 days'));
-
if ($visits == 0) {
-
echo 'I have never seen you before, but I am glad you are here :)';
-
}
-
else {
-
echo 'Welcome back! You have been here ', $visits, ' time(s) before';
-
}
-
?>
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.
-
<?php echo "http://www.yoursite.com/yourphppage.php?PHPSESSID=" . session_id();" ?>
-
Then use the following in the loading page to retrieve the session id:
-
<?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
- <?php
-
session_start();
-
$visits = $_SESSION['visits']++;
-
if ($visits == 0) {
-
echo 'I have never seen you before, but I am glad you are here :)';
-
}
-
else {
-
echo 'Welcome back! You have been here ', $visits, ' time(s) before';
-
}
-
?>
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.