Php Cookie Example
Cookies are an important part of php and web development in general. Since http is a stateless protocol (This means that the server forgets each client after a connection), web developers need a way to store user preferences or allow their scripts to remember details about each client. Cookies take on to solve this problem. (There are other solutions like sessions which is a great one or query strings which are less preferable).
For this example we will use
- A computer with PHP 5.5 installed.
- notepad++.
1. Getting Started
To demystify cookies in php, we will develop a simple web app that allows users to select the font style and font size to display on a website and store this preference.
1.1 Working With Cookies
Cookies identify a user. They allow web developers to store a small amount of data on the user browser(not more than 4kb). Each time a request is sent to the server, the cookies stored on the browser are automatically sent with the request and can be accessed by the server.
Cookies are reliable but they are not that secure because attackers can easily tamper with them. Thus you should never use cookies alone to authenticate your users or store sensitive data in cookies (e.g passwords). Users have the possibility to turn off cookies support in there browsers, so you should be careful when the core functionality of your web app depends on cookies. (If your web app depends on cookies to work properly, you should always check if cookies are supported in the browser and if it is not, alert the user about the error.)
1.2 Creating cookies in php
To create a cookie in php we use the setcookie(name,value,expires,path,domain,secure,httponly)
function, which takes 7 parameters.
1.3 Cookie field and their description
- Name: This is the name of the cookie.
- Value: This is the value of the cookie.
- Expires: This is the time the cookie will expire. If this value is set to a past time or if the time is already reached, the cookie is deleted from the browser. If the value is set to zero or is omitted the cookie lasts as long as the browser is running and then it automatically deleted when the browser exits.
- Path: The path that the browser should send the cookie back to. If specified, the browser will only send the cookie to urls that contain this path. If a value is not specified for this field, the current directory is assumed.
- Domain: The (sub)domain that the cookie is available to.
- Secure: It is a boolean value, which indicates whether the cookie should be transmited over a secure (https) 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.
1.4 Code
index.php
<?php if (isset($_POST["size"])){ $size=$_POST["size"];//check if the size variable is set setcookie("size", $size,0,"/","",false,true); } if (isset($_POST["font"])){ $font=$_POST["font"];//check if the size variable is set setcookie("font", $font,0,"/","",false,true); } ?> <!DOCTYPE html> <html lang=eng> <head> <title> Dynamic php and html table testing </title> <style> html, body{ width:100%; height:100%; margin:0%; font-family:"helvetica","verdana","calibri", "san serif"; overflow:hidden; padding:0%; border:0%; } p{ font-size:<?php if(isset($_COOKIE["size"])) echo $_COOKIE["size"]; else echo "1em" ?>; font-style:<?php if(isset($_COOKIE["font"])) echo $_COOKIE["font"]; else echo "italic" ?>; } </style> </head> <body bgcolor="#e5a010"> <p> What Is PHP? PHP is a programming language for building dynamic, interactive Web sites. As a general rule, PHP programs run on a Web server, and serve Web pages to visitors on request. One of the key features of PHP is that you can embed PHP code within HTML Web pages, making it very easy for you to create dynamic content quickly. </p> <p> What exactly does the phrase "dynamic, interactive Web sites" mean? A dynamic Web page is a page whose contents can change automatically each time the page is viewed. Contrast this with a static Web page, such as a simple HTML file, which looks the same each time it's displayed (at least until the page is next edited). Meanwhile, an interactive Web site is a site that responds to input from its visitors. A Web forum is a good example, users can post new messages to the forum, which are then displayed on the site for all to see </p> <div> <form method=post action=index.php> <label>Choose Font Style</label> <select name=font> <option value="normal"> Normal </option> <option value="italic"> Italic </option> </select> <label>Choose Font Size</label> <select name=size> <option value="1em"> 1 </option> <option value="2em"> 2 </option> </select> <input type=submit value="Submit Form"> </form> </div> </body> </html>
In line 2 and line 7 we use the isset()
function to check if the user has chosen a font size and font style.(It is a good practice to check if a form value is present before using it). If the user has chosen a font style and font size we call the setcookie()
method to create the cookie on the browser. In line 4 we created a cookie named size which stores the font size while in line 7 we created a cookie named font which stores the font style.
In lines 29 and 30 we checked to see if a cookie has been created. If the cookie is available we use its value to set the font style and size in css. If a cookie has not been transmitted to the browser we set the font style and size to a default value. Cookies can be accessed with $_COOKIE
global variable.
When the browser is closed the size and font cookies are deleted, since we set the time value to zero. To allow the cookie to last longer than the current browser season, we supply a time value in the future. setcookie("font", $font,time()+60*60*24,"/","",false,true);
the time()
function returns the current time in UNIX timestamp format. So the expiry time is 60 * 60*24 plus the current time(so the cookie would expire one day from the current time). You might need to refresh your browser to see the result of your selections.
1.5 Deleting Cookies In Php
delete.php
<?php if (isset($_COOKIE["size"])){ setcookie("size", $size,time()-60 *60*24,"/","",false,true);//cookie named size is deleted by set time option to a time in the past } if (isset($_COOKIE["font"])){ setcookie("font", $font,time()-60 *60*24,"/","",false,true);//cookie named font is deleted by set time option to a time in the past } ?> <!DOCTYPE html> <html lang=eng> <head> <title> Dynamic php and html table testing </title> <style> html, body{ width:100%; height:100%; margin:0%; font-family:"helvetica","verdana","calibri", "san serif"; overflow:hidden; padding:0%; border:0%; } p{ font-size:<?php if(isset($_COOKIE["size"])) echo $_COOKIE["size"]; else echo "1em" ?>; font-style:<?php if(isset($_COOKIE["font"])) echo $_COOKIE["font"]; else echo "italic" ?>; } </style> </head> <body bgcolor="#e5a010"> <?php if(!isset($_COOKIE["size"])) echo "<p>cookie named size has been deleted</p>"; if(!isset($_COOKIE["font"])) echo "<p>cookie named font has been deleted</p>"; ?> <p> What Is PHP? PHP is a programming language for building dynamic, interactive Web sites. As a general rule, PHP programs run on a Web server, and serve Web pages to visitors on One of the key features of PHP is that you can embed PHP code within HTML Web pages, making it very easy for you to create dynamic content quickly. </p> <p> What exactly does the phrase "dynamic, interactive Web sites" mean? A dynamic Web page is a page whose contents can change automatically each time the page is viewed. Contrast this with a static Web page, such as a simple HTML file, which looks the same each time it's displayed (at least until the page is next edited). Meanwhile, an interactive Web site is a site that responds to input from its visitors. A Web forum is a good example, users can post new messages to the forum, which are then displayed on the site for all to see </p> </body> </html>
In lines 2 and 6 we checked if there were cookies available and deleted them if they existed in the browser request. (They were deleted by setting the time argument to a certain time in the past). You might need to refresh your browser to see the result.
2. Summary
In this example we learnt about cookies, there importance, and how to create and delete them in php. We also learnt about their benefits and drawbacks.