Sie sind auf Seite 1von 5

Cookies and Sessions Owing to the fact that HTTP is stateless - that is, any data you have

stored is forgotten about when the page has been sent to the client and the connection is closed - it took a little work to find a solution to the problem. Eventually, Netscape put a solution into their browser known as "cookies" - tiny bits of information that a web site could store on the client's machine that were sent back to the web site each time a new page was requested. Each cookie could only be read by the web site that had written it, meaning that it was a secure way to store information across pages. Cookies earned a bad name at first because they allowed people to track how often a visitor came to their site, what they did on the site, and such, and many people believed that cookies signalled the end of privacy on the web. Urban myths popped up in many places saying that cookies can read any information from your hard drive, and people were encouraged to disable cookies across the board. The reality is, of course, that cookies are relatively harmless, and are now commonly accepted. Sessions grew up from cookies as a way of storing data on the server side, because the inherent problem of storing anything sensitive on clients' machines is that they are able to tamper with it if they wish. In order to set up a unique identifier on the client, sessions still use a small cookie - this cookie simply holds a value that uniquely identifies the client to the server, and corresponds to a data file on the server. Topics covered in this chapter are: How cookies and sessions compare Which to use and when How to use sessions Using a database to store your sessions Storing complex objects 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. Cookies A cookie, as already mentioned, is a tiny little file on your client's hard drive which contains data you have asked to be stored. Some clients specifically configure their browser to reject cookies, believing for one reason or another that they are malicious, and there is nothing you can do about this - that person's browser will not be able to store your data. When creating cookies, you specify how long you want it to be valid for, and, once done, the cookie remains in place until that date, when it "expires". Author's Note: Are cookies dangerous? No, not at all - a web-site can only read data it stored, and it can only store a small amount of data. The only possible danger to cookies is that they can store information about you

without you realising it - a web-site can track how often you visit, what times you visit at, what banners you clicked, etc. However, they cannot read your credit card number, raid your fridge, or anything of the sort! Cookies are automatically sent to the web server (and received/parsed by PHP) each time a user visits you. That means that once we place our cookie, our visitors' browsers will automatically send the contents of that cookie across to us each time they view our messageboard index, and PHP will read the value into the $_COOKIE superglobal array. As cookies are sent each time, it is incredibly important not to store too much information there - they can really waste a lot of bandwidth. The nice thing about cookies is that they are decentralised - you do not need to worry about creating databases to hold information or adding and removing rows, you just store the data and check whether it is set. As such, cookies are good for any pages where you have got a small amount of information to handle usually this involves user preferences. For example, use cookies to store how users want their messageboard index sorting, what order they like their news printed, etc. If you are storing information such as their email address, ICQ number, etc, you should probably use a database - data like that is generally stored for long periods of time, whereas cookies are usually more throwaway information. That said, if you are storing personal information in cookies, please take the time to encrypt it. Sessions Sessions are a combination of a server-side cookie and a client-side cookie, with the client-side cookie containing nothing other than a reference to the correct data on the server. Thus, when the user visits the site, their browser sends the reference code to the server, which loads the corresponding data. This may seem a bit clumsier than just having a client-side cookie with all your data in, but there are a few advantages: Your server-side cookie can contain very large amounts of data with no hassle - client-side cookies are limited in size Your client-side cookie contains nothing other than a small reference code - as this cookie is passed each time someone visits a page on your site, you are saving a lot of bandwidth by not transferring large client-side cookies around Session data is much more secure - only you are able to manipulate it, as opposed to client-side cookies which are editable by all It is also important to note that sessions only last till the user closes their browser, whereas cookies can be configured to last longer. However, other than the above, there is not much difference between session data and cookie data for most purposes. 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. The end result? They lose their information part-way through their visit, and what data you do have is fragmented across your servers. There are ways around this problem, never fear: Use a networked file system (NFS on Unix or the equivalent). Pretty much all operating systems allow you to connect to other computers and read/write their data. If you have a shared session data source, you would be able to bypass the above problem Write your own session implementation that stores data in a medium you can handle and share between all computers. This is tricky, and error-prone. Use a database to store your sessions. Using cookies bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

Taking the example of sorting a messageboard index, a cookie would need to be placed that holds the user's preference on message sorting - whether they want it newest first, oldest first, or sorted alphabetically. Take a look at this piece of code: <?php if (!isset($_COOKIE['Ordering'])) { setcookie("Ordering", $_POST['ChangeOrdering'], time() + 31536000); } ?> <form method="post" action="mbprefs.php"> Reorder messages: <select name="ChangeOrdering"> <option value="DateAdded ASC">Oldest first</option> <option value="DateAdded DESC">Newest first</option> <option value="Title ASC">By Title, A-Z</option> <option value="Title DESC">By Title, Z-A</option> </select> <input type="submit" value=" Save Settings " /> </form> The script can be split up into two distinct parts - first we check whether a cookie is set, and, if not, we use the setcookie() function to set it. Then we output a form allowing visitors to select how they'd like their ordering set. The setcookie() call needs to be before the HTML form because of the way the web works. The explanation requires a little knowledge of how HTTP works and is quite important if you want to understand how cookies work, but never fear - I will try to keep it as simple as possible! HTTP operates by sending all "header" information before it sends "body" information. In the header, it sends things like server type (e.g. "Apache"), page size (e.g. "29019 bytes"), and other important data. In the body, it sends the actual HTML you see on the screen. HTTP works in such a way that header data cannot come after body data - you must send all your header data before you send any body data at all. Cookies come into the category of header data - when you place a cookie using setcookie(), your web server adds a line in your header data for that cookie. If you try and send a cookie after you have started sending HTML, PHP will flag up serious errors and the cookie will not get placed. There are two ways to correct this: Put your cookies near the top of your page. By sending them before you send any body data, you avoid the problem entirely. Enable output buffering in PHP. This allows you to send header information such as cookies wherever you like - even after (or in the middle of) body data. Output buffering is covered in depth in its own chapter. The setcookie() function itself takes three main parameters: the name of the cookie, the value of the cookie, and the date the cookie should expire. Author's Note: One important thing to remember about cookies is that they are sent to the server each time a user visits a page. So, if you set a cookie in a script, it does not become available until your user visits the next page (or hits refresh) - this often confuses people who are desperately hunting for a bug. In the example code, setcookie() sets a cookie called "Ordering" to the value set in the form from the drop down SELECT box, and it uses time() + 31536000 as its third parameter - this is equal to the current time in seconds plus the number of seconds in a year, which means the cookie is set to expire one year from the time it was set. Once set, the Ordering cookie will be sent with every subsequent page request, and PHP will make it available in $_COOKIE. Note that users can clear their cookies manually, either by using a special option in their web browser or just by deleting files. It is also important to note that cookies are sent from your visitor to you when the page is requested - if you set the cookie during the PHP script that is requested, it will not have been sent with the request, which means it will not be in $_COOKIE - this is what is meant by "every subsequent page request"!

The last three parameters of the setcookie() function allow you to restrict when it's sent, which gives you a little more control. They aren't used often, but, in case you were interested, here's how they work: Parameter four ("path") allows you to set a directory in which the cookie is active. By default, this is "/" (active for the entire site), but you could set it to "/messageboards/" to have the cookie only available in that directory and its subdirectories. Parameter five ("domain") allows you to set a subdomain in which the cookie is active. For example, specifying "mail.yoursite.com" will make the cookie available there but not on www.yoursite.com. Use ".yoursite.com" to make the cookie available everywhere. Parameter six ("secure") lets you specify whether the cookie must only be sent through a HTTPS connection or not. The default, "0", has the cookie sent across both HTTPS and HTTP, but you can set it to 1 to force HTTPS only. Using sessions Sessions are great for storing temporary data about your visitors, particularly when you do not want that data to be accessible from outside of your server. Using sessions before PHP 4.1 was much harder than it is today if you are used to having to use functions to set and unset session variables, you should pay extra-special attention to this text on sessions, because things have changed substantially as a result of the superglobal $_SESSION array. Starting a session bool session_start ( void ) A session is a combination of a server-side file containing all the data you wish to store, and a client-side cookie containing a reference to the server data. The file and the client-side cookie are created using the function session_start() - it has no parameters, but informs the server that sessions are going to be used. When you call session_start(), PHP will check to see whether the visitor sent a session cookie - if it did, PHP will load the session data. Otherwise, PHP will create a new session file on the server, and send an ID back to the visitor to associate the visitor with the new file. Because each visitor has their own data locked away in their unique session file, you need to call session_start() before you try to read session variables - failing to do so will mean that you simply will not have access to their data. Furthermore, as session_start() needs to send the reference cookie to the user's computer, you need to have it before the body of your web page - even before any spaces. Adding session data All your session data is stored in the session superglobal array, $_SESSION, which means that each session variable is one element in that array, combined with its value. Adding variables to this array is done in the same way as adding variables to any array, with the added the bonus that session variables will still be there when your user browses to another page. To set a session variable, use syntax like this: $_SESSION['var'] = $val; $_SESSION['FirstName'] = "Jim"; Older versions of PHP used the function session_register(), however use of this function is strongly discouraged, as it will not work properly in default installations of PHP 5. If you have scripts that use session_register(), you are strongly recommended to switch over to using the $_SESSION superglobal, as it is more portable, and easier to read too. Before you can add any variable to a session, you need to have already called the session_start() function don't forget! Author's Note: you cannot store resources such as database connections in sessions, nice as that might be, because these resources are unique to each PHP script, and are usually cleaned when that script terminates. While this may change in the future, it is not likely. Reading session data Once you have put your data safely away, it becomes immediately available in the $_SESSION superglobal array with the key of the variable name you gave it. Here is an example of setting data and reading it back out again:

<?php $_SESSION['foo'] = 'bar'; print $_SESSION['foo']; ?> Unlike cookies, session data is available as soon as it is set, which can be quite an advantage. Removing session data Removing a specific value from a session is as simple as using the function unset(), just as you would for any other variable. It is important that you should unset only specific elements of the $_SESSION array, not the $_SESSION array itself, because that would leave you without any way to manipulate the session data at all. To extend the previous script to remove data, use this: <?php $_SESSION['foo'] = 'bar'; print $_SESSION['foo']; unset($_SESSION['foo']); ?> Ending a session bool session_destroy ( void ) A session lasts until your visitor closes their browser - if they navigate away to another page, then return to your site without having closed their browser, their session will still exist . This behaviour is usually desirable potentially your visitor's session data might last for days, as long as they keep browsing around your site, whereas cookies usually have a fixed lifespan. If you want to explicitly end a user's and delete their data without them having to close their browser, you need to clear the $_SESSION array, then use the session_destroy() function. Session_destroy() removes all session data stored on your hard disk, leaving you with a clean slate. To end a session and clear up its data, use this code: <?php session_start(); $_SESSION = array(); session_destroy(); ?> There are two important things to note there: firstly, session_start() is called so that PHP loads the user's session, and secondly we use an empty call to the array() function to make $_SESSION an empty array effectively wiping it. If session_start() is not called, neither of the following two lines will work properly, so, again, always call session_start()! Checking session data You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable. For example: <?php session_start(); if (isset($_SESSION['FirstName'])) { /// your code here } ?> You can, of course, also use the empty() function with session data, or indeed any other function - the $_SESSION array and its data can be used like any other array.

Das könnte Ihnen auch gefallen