COOKIES IN PHP
Cookies: Simply it is the information stored in the user’s computer by the Web Server.
Information stored:
- String of text that contains information about the browser
- Some cookies store personal information about the user
Need:
- To identify the user and possibly prepare the customized website or to save site login information of the user.
- The website can remember the user and load his preferences whenever that particular user access that website again.
Cookies Capabilities
Instead of seeing just a generic welcome page the user might see a welcome page with his/her name on it.
Types of Cookies
Session cookie
Also called a transient cookie, a cookie that is erased when the user closes the Web browser. The session cookie is stored in temporary memory and is not retained after the browser is closed. Session cookies enable the website that the users are visiting to keep track of their movements from page to page so that they don’t get asked for the same information which they have already given to the site. The most common example of this functionality is the shopping cart feature of any e-commerce site.
Persistent cookie
Also called a permanent cookie, or a stored cookie, a cookie that is stored on the user’s hard drive until it expires (persistent cookies are set with expiration dates) or until one deletes the cookie. Persistent cookies help websites remember user’s information and settings when any user visits them in the future. This results in faster and more convenient access since, for example, the user don’t have to login again.
Features made possible by persistent cookies include: language selection, theme selection, menu preferences, internal site bookmarks or favourites, among many others.
Cookies In PHP
A cookie is created with the setcookie() function.
Syntax
1 |
setcookie(name,value,expiry,path,domain,secure,httponly) |
Only the name parameter is required. All other parameters are optional.
set.php
1 2 3 |
<?php setCookie(“username”,”Anuj”,); ?> |
view.php
1 2 3 |
<?php echo “The cookie ”.$_COOKIE[username]”.is set”; ?> |
Output of set.php after set.php is opened
The cookie mudit is set
Note!!:
If the html coding lies within the same php page, then setcookie() should appear before the tag.
Modifying a cookie- very simple just set the cookie again using the setcookie() function.
Deleting a cookie: Give the expiry time parameter while setting the cookie.
1 2 3 4 5 6 7 8 9 10 11 |
<?php // set the expiration date to one hour ago setcookie("user", "", time() - 3600);//time()-get the timespan ?> <html> <body> <?php echo "Cookie 'user' is deleted."; ?> </body> </html> |
Drawbacks of cookie-
- Cookies can be manipulated by the client. This causes security issues.
- The server can be sent wrong values by the user.
- As they are being stored in the client machine, they can be deleted intentionally as well as mistakenly by the user
- Persistent cookies will require memory space of the client machine to be stored