PHP Tutorial: Cookies vs Sessions
If you’re interested in making any kind of web based application then learning how to use sessions and cookies is a must. Many people don’t understand how these work and how they different from each other, and why you would choose to use one versus the other. So put on your thinking caps and let’s get started.
What is a Cookie?
A cookie is a data file that’s written to your browser’s localStorage with data you want to keep track of for a user. So what’s localStorage? The best real world analogy I can give you is to think about it like a 3 ring binder that you can add, update and remove files from. In this example a cookie would be a piece of paper in your 3 ring binder.
How Do Cookies Work?
When you navigate around the Internet your browser is constantly sending and receiving information from the websites you want to access. These are called HTTP headers. HTTP headers contain important information about the requests and responses being sent back and forth from a browser to a server. When someone has an active cookie from your website in their browser’s localStorage it automatically passed in the HTTP headers to the site of origin in the $_COOKIE variable of PHP. Since headers have to be sent before any output setting a cookie must always go at the top of your file.
How do I Create a Cookie?
<?php $name = "myCookie"; $value = "hello world!"; $expires = time() + 60 * 60 * 24; //1 day $path = "/"; $domain = "yourwebsite.com"; $secure = 0; //0 for false, 1 for true $httponly = 0; //0 for false, 1 for true //let's tell the browser to create our cookie setcookie($name, $value, $expires, $path, $domain, $secure, $httponly); //let's make a cookie array too setcookie("cookieArray[0]", "A"); setcookie("cookieArray[1]", "B"); setcookie("cookieArray[2]", "C"); //you must refresh the page before your new cookies are visible echo "refresh the page to see your cookies: " . $_COOKIE['myCookie']; //this will loop through and display your array cookies foreach ($_COOKIE['cookieArray'] as $key => $value) { echo "<br/>array cookie $key => $value"; } ?>
In this first example we’ve created a cookie called myCookie that stores the value of hello world! In order to see something printed on the screen you must refresh the page. This is because the HTTP headers must be sent from the server to your browser and then from your browser back to the server before they show up in the $_COOKIE variable.
Expires is an optional value that tells the browser how long to keep our cookie before it deletes it. By using the current time() and then adding on an extra 24 hours our cookie will only stick around for a day before the browser deletes it. So in this example if your cookie is created at today at 12noon EST it will expire tomorrow at 12noon EST. When your cookie is expired you’ll have to create a new one if you want to store your $value again.
Next we’ve set a path for our cookie. This is also an optional field and will default to / if you don’t give it a value. This tells the browser where this cookie will be available. So let’s say your website is http://yourwebsite.com and you only want this cookie to be available when you’re inside the http://yourwebsite.com/users/ section or your website. If that were the case we’d change the path to /users/ and then our cookie will only be accessible when we’re in the users directory. When we leave the path at / it means our cookie is available on any part of the domain we’ve given it.
The domain of your cookie is optional. If you don’t provide a domain for your cookie it may default to your current domain name. You can also set your domain name to a subdomain. So for instance, if we had a subdomain of http://users.yourwebsite.com we would set our domain to users.yourwebsite.com then our cookie would only be available when we’re inside our users subdomain.
The secure section of the cookie is optional and should only be set to true if you’re using https.
The httponly is optional and tells newer browser to only make your cookie accessible in the HTTP header. Not all browsers support this functionality, however it has been added to help prevent against cross site scripting (XSS) attacks.
How do I Access Cookie Values?
<?php //this shows you a single cookie echo $_COOKIE['myCookie']; //this shows you all available cookies print_r($_COOKIE); ?>
Once you have a cookie set you can access it by using the $_COOKIE variable in PHP and then pass it the name of the cookie you want to access or you can use a print_r() call to print all available cookies.
How do I Delete a Cookie?
<?php //unset the single cookie unset($_COOKIE['myCookie']); //unset the array cookies unset($_COOKIE['cookieArray']); //update the cookie's expiration date to sometime in the past setcookie("myCookie", false, time()-1); setcookie("cookieArray[0]", false, time()-1); setcookie("cookieArray[1]", false, time()-1); setcookie("cookieArray[2]", false, time()-1); ?>
Sometimes you want to remove a cookie. There are two different ways to do this. The first is to unset() the cookie and the second is to update the expiration date to a time in the past which will force your browser to remove it. Just like when we set a cookie, you must refresh the page before you will see that your cookie has been removed.
How do I Edit a Cookie?
<?php //to edit a single cookie value setcookie("myCookie", "My new value"); //to edit a cookie array setcookie("cookieArray[0]", "one"); setcookie("cookieArray[1]", "two"); setcookie("cookieArray[2]", "three"); ?>
As long as the cookie exists all you need to do is set the cookie with the same name and give it a different value. You won’t see that the values in your cookie have changed until you refresh the page since cookies are sent in an HTTP header.
Cookie Trouble Shooting
- If you’re having trouble setting a cookie and you’re getting a headers already sent error then you have some kind of output (text, spaces, html, images, etc) that are being displayed to the screen before you’re calling your setcookie() function.
- Once you’ve added, edited or deleted a cookie you must refresh the page before you can see that your changes have taken place. This is because cookies are sent in HTTP headers.
- Cookies must be deleted with the exact same parameters as they were set with.
- Cookie arrays are stored as one file for each index in the array. For this reason large arrays are not recommended. If you need to store lots of data in a cookie it’s more useful to use a single cooke and concatenate the values with implode() then retrieve the data using explode().
- If one of the values in your cookie resolves to a false your cookie will be deleted. For this reason you shouldn’t use true/false booleans but instead use 0 and 1.
- It is not recommended to serialize your cookie values as this can cause security holes.
- If the user’s browser has cookies disabled or will not allow cookies to be stored then you won’t be able to create a cookie in their localStorage. This problem gave rise to the creation of sessions.
What Is a Session?
Sessions are the best solution for short term storage of data and dealing with user’s browsers that don’t allow the creation of cookies. Sessions will attempt to create a cookie and if the attempt fails will instead propagate via the URL. However a session will only persist over the duration of a user’s visit on your website. Once the user leaves your site the cookie (if one was created) is deleted so there is no persistent information retained about the user in the browser’s localStorage once they’ve left your website.
How do I Create a Session?
<?php //you have to start the sessions before you can use them session_start(); //set a single session value $_SESSION['mySession'] = "hello world!"; //set an array in a session $_SESSION['myArray'] = new array('A', 'B', 'C'); //set an object in a session $_SESSION['myObject'] = new myObject(); //this tells php your done making changes to the session session_write_close(); //session values are immediately available echo $_SESSION['mySession']; print_r($_SESSION['myArray']); print_r($_SESSION['myObject']); ?>
All sessions must be started with the session_start() call unless you have them set to auto start in your php.ini file. Usually this isn’t the case with most hosting providers. In addition session_start can take parameters to configure the length of the session and the storage location, etc, however most hosting providers don’t let you change these settings so I won’t cover them here.
Sessions are sent via HTTP headers just like cookies are (when PHP tries to create a temporary cookie), however since they can persist without cookies the data is immediately accessible once it has been initialized. This means you won’t have to refresh the page to access the data you’ve stored in them.
How do I Access Session Values?
<?php session_start(); echo $_SESSION['mySession']; print_r($_SESSION['myArray']); print_r($_SESSION['myObject']); ?>
Unlike cookies where you have to refresh the page before you can access them, session values are immediately available once they’ve been set. All you have to do is start the sessions (unless sessions have been set to auto start) and then look for the name of the session you want to access.
How do I Delete a Session?
<?php session_start(); //remove a single session values unset($_SESSION['mySession']); unset($_SESSION['myArray']); unset($_SESSION['myObject']); //alternative way to remove a session values $_SESSION['mySession'] = false; $_SESSION['myArray'] = null; $_SESSION['myObject'] = ''; //this tells php your done making changes to the session session_write_close(); //remove all session values session_destroy(); ?>
The best way to remove a session is to unset it, however you can also set the value to falsey or call session_destroy() to remove all session values.
How do I Edit Session Values?
<?php //you have to start the sessions before you can use them session_start(); //edit a single session value $_SESSION['mySession'] = "new value!"; //edit an array in a session $_SESSION['myArray'] = new array('one', 'two', 'three'); //edit an object in a session $_SESSION['myObject'] = new myNewObject(); //this tells php your done making changes to the session session_write_close(); //session value changes are immediately available echo $_SESSION['mySession']; print_r($_SESSION['myArray']); print_r($_SESSION['myObject']); ?>
You can edit session values the same way you set them initially.
Session Troubleshooting
- If you’re having trouble getting a session started and you’re getting headers already sent errors then you have some kind of output (text, spaces, html, images, etc) that are being displayed to the screen before you’re calling your start_session() function.
- Sessions will only last for the duration of a user’s visit or for the session_expiration time that’s set in the php.ini file. You can learn more about session configuration values in the PHP manual.
- Make sure you’re not doing an unset($_SESSION) as this will make it impossible to register any new values in the $_SESSION.
- You can’t use reference variables in sessions.
- If register_globals are enabled they will overwrite variables with the same $_SESSION name. For instance if you have a session named mySession and register_globals is enabled and you create a $mySession variable it will overwrite the $_SESSION[‘mySession’] value with whatever you’ve assigned to $mySession.
- If you’re having a problem changing values in your session make sure you’re calling session_write_close() after you’ve made changes to session values. This is especially important if you’re doing a lot of asynchronous ajax calls.
Should I Use a Session or a Cookie?
The best way to answer this question is do you need data on a user to persist once they’ve closed their browser? Sessions will only last for the duration of a user’s visit on your website, they will disappear as soon as the user has closed all windows and tabs that they have open for your website. Cookies, on the other hand, will remain on a user’s computer until the user removes them from their browser or they expire.
Pros & Cons of Sessions vs Cookies
Type | Pros | Cons |
---|---|---|
Sessions | Excellent for short term data storage
Can access immediately after initialization Will create a temporary cookie if cookies are enabled/supported, otherwise propagated on the URL Can be used for authentication |
Only last for the duration of the user’s visit
Susceptible to XSS attacks |
Cookies | Excellent for long term storage of data
Can be used for authentication |
Must be enabled/supported on the browser
Must refresh the page before you can access cookie data Susceptible to XSS attacks |