PHPBuilder - Tips for Using Session Cookies with PHP

RSS Twitter

Tips for Using Session Cookies with PHP

by: Octavia Andreea Anghel
December 11, 2015

A session cookie, also known as a transient cookie, is named like that because exists only temporary during the time that the user navigates the website, so when the user closes the browser, the session cookies are deleted. Websites normally use session cookies to make sure that you are recognized when you navigate from different pages within a site and that any information you have provided is remembered. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user's browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). Cookies can also store passwords and form content a user has previously entered, such as a credit card number or an address. Without a cookie, every time you open a new web page, the server where that page is stored will treat you like a completely new visitor. You can adjust your session cookies through the settings feature of your browser.


Cookies are plain text files, they are not compiled so they cannot execute functions or make copies of themselves. They cannot browse through or scan your computer or otherwise snoop on you or dig for private information on your hard disk. Cookies have a very limited function: to help your browser deliver the full features designed into many of today's websites. These features include smooth login, preference settings, themes, shopping carts, and many other features. Cookies cannot scan or retrieve your personal information. As I mentioned above, the most popular uses of cookies are: to store username/password information so that the user doesn't have to log in every time they visit the website ("remember me" sign-ins), to simply remember the user's name, to keep track of a user's progress during a specified process, to remember a user's theme.


What can I do to manage cookies stored on my computer?

As you certainly notice, when you navigate on different websites, you got this message: "This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies. Find out more here." This message appears because of the European Directive 2009/136/CE  that urges to alert to the user and ask for an approval of the current website Cookies Policy. According to this directive, the Cookies Policy Notification Portlet notifies every user who accesses the website for the first time the terms of that portal Cookies Policy.


The notification may contain a message which includes the reason, a link to any other page where the complete policy would be explained (i.e. how to remove or disable the current portal cookies) and also a tacit consent therefore I accept this policy if I continue accessing portal pages. Different browsers offer differing ways to configure your browser's cookie settings. Due to the wide range of differences among various website's privacy policies, many browsers allow for universal privacy settings from which users can choose. Users can choose differing privacy settings based on their particular privacy concerns. Most commercial and/or professionally-created websites like Yahoo and Google have privacy policy pages that disclose how the sites handle, gather, and/or pass on user information to third parties. These are known as "P3P" features (Privacy Preferences Platform).


Cookies in PHP

PHP transparently supports HTTP cookies, as we said earlier, the cookies are a mechanism used to store data in the remote browser and for tracking or identifying return users. In PHP you can set cookies using the setcookie() or setrawcookie() function, described below. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array.


The two PHP function used for setting cookies are setcookies() and setrawcookies(), both described below:


   • setcookie() defines a cookie to be sent throughout with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function before any output, including <html> and <head> tag. The cookies can be accessed only after they have been set, on the next page load using the $_COOKIE array. Cookie values may also exist in $_REQUEST. The setcookie() method syntax is:


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


where:  • name represents the name of the cookie;


 • value parameter represents the value of the cookie, that is stored on the clients computer (as an example, if the name is MyCookie, this value is retrieved through $_COOKIE[' MyCookie ']);


 • expire parameter is the time until cookies expire, to set that parameter you need to use the time() function plus the number of seconds before you want it to expire (per example, you can set the time of the cookie expiration after 7 days like that:

time() + (86400 * 7));  86400=24h*60min*60sec


 • path on the server in which the cookie will be available on;


 • domain is the domain that the cookie is available to;


 • secure parameter indicates that the cookie should only be transmitted over a secure HTTPS connection from the client;


 • 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.


   • setrawcookie() is exactly the same as setcookie() the only difference is that the cookie value will not be automatically urlencoded when sent to the browser.


In the next section, we will see some of the most used operations of the cookies in PHP.


1. Setting new cookie and getting the cookie

The listing below sets the cookie named 'test', with the value 'Cookie' and the expiration date after 7 days, using the above described function setcookie(). The result, the 'test' cookie, can be seen into the below printscreens of the browsers, in our case Mozilla Firefox and Google Chrome, using the two corresponding extensions for cookies: Firebug and HTML5 Storage Manager All in One:


$cookie_name = "test";
$cookie_value = "Cookie";

//setting the cookie name, value and expiration date - after 7 days
setcookie($cookie_name, $cookie_value, time() + (86400 * 7), "/"); 

//listing the cookie
echo $_COOKIE["test"];


Checking the cookie using the Mozilla Firefox extension, Firebug



Checking the cookie using the Google Chrome extension, HTML5 Storage Manager All in One




2. Accessing Cookies with PHP

The simplest way to access cookies in PHP, is to use $_COOKIE that is an associative array of variables passed to the current script via HTTP Cookies. Following example set and access three cookies:


   setcookie("name", "Rafa Nadal", time()+3600, "/","", 0);
   setcookie("age", "28", time()+3600, "/", "",  0);
   setcookie("RolandGarros", "9", time()+3600, "/", "",  0);
   echo $_COOKIE["name"]. " ----- ". $_COOKIE["age"]." ----- ".$_COOKIE["RolandGarros"];


Accessing the three cookies setted in the above listing


3. Updating Cookie

To update a cookie, all you need to do is to set the cookie again, using the setcookie() method:


   setcookie("name", "Rafa Nadal", time()+3600, "/","", 0);
   setcookie("age", "29", time()+3600, "/", "",  0);
   setcookie("RolandGarros", "9", time()+3600, "/", "",  0);
   //updating the cookie 'name'
   setcookie("name", "Roger Federer", time()+3600, "/","", 0);
   echo $_COOKIE["name"]. " ----- ". $_COOKIE["age"]." ----- ".$_COOKIE["RolandGarros"];


Modify a cookie


4. Deleting Cookie

To delete a cookie, you must set the time parameter as expired, so that cookie will be deleted automatically, as you can see in the below example. Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie(), then the cookie with the specified name will be deleted from the remote client.


	//the cookie is expired, so it will be deleted
	setcookie("age", "56", time()-3600);

	//deleting the cookie by setting the value argument FALSE or an empty string
      setcookie("age", "FALSE", time(), "/", "",  0);
      setcookie("age", "", time(), "/", "",  0);


Deleting the 'age' cookie


5. Check if Cookies are Enabled

To check if cookies are enabled we need to use the count() function, like in the below listing:



setcookie("name", "Rafa Nadal", time()+3600, "/","", 0);

if(count($_COOKIE) > 0) {
    echo "Cookies are enabled.";
} else {
    echo "Cookies are disabled.";



This article as explored what the cookies are and why are they useful, how to set a cookie and make different operations over it.


Comment and Contribute

Your comment has been submitted and is pending approval.

Octavia Andreea Anghel



(Maximum characters: 1200). You have characters left.