Rating: 1 Star2 Stars3 Stars4 Stars5 Stars
Loading...

PHP Howto- Session and Cookies

Developers are often find Session and cookies to be same but there is one major difference. Sessions are stored on server while cookies are stored on clients machine. Cookies can easily be tampered by an expert hacker where as session is somewhat safe. Still, cookies are used in many web applications. You must have seen “Remember me on this computer” check box.


What is a cookie?

Sometimes it becomes necessary to track certain user details like (No. Of Visits, names, last visit, etc). The client machine stores such information and sends it to the web server whenever there is a request. Cookies data are sent along with the HTTP headers. You can look at this URL to know more about how they work. http:\\www.cookiecentral.com\faq\


Difference between session and cookie?

The key difference would be cookies are stored in your hard disk whereas a session aren’t stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.

Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.

Note: When you issue a session_start() it generates a session ID and places that on the client side in a cookie. There are also some ways to avoid this using the tag rewrite.


How secure is storing password using cookies?

Generally we store the cookies with the username followed by the password. Now we can use any algorithm to encrypt the password before we store then to make it secured. Now we will have the user name and encrypted password stored in the cookie, which again can be played around. A good practice would be to avoid the storing of user name and using a unique ID generated. This is a overhead which we have to compromise to make thinks more secure.


PHP Cookie Function

As told earlier cookie is sent along with the HTTP headers and to do this we have the set_cookie() function.

boolean setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]] )

All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace any argument with an empty string (“”) in order to skip that argument. The expire and secure arguments are integers and cannot be skipped with an empty string. Use a zero (0) instead. The expire argument is a regular Unix time integer as returned by the time() or mktime() functions. The secure indicates that the cookie should only be transmitted over a secure HTTPS connection.


Common Errors

Warning: Cannot modify header information – headers already sent by….

Always ensure there are no white spaces or HTML tags before the cookie function. When you start with a blank line in your PHP file there is a possibility of getting this error.

Quick Code.

This example will allow you to save user name and password on the client PC as cookie and retrieve them when needed.

There are totally three “.php” files used and let me give a short introduction about what they do.

Index.php

This page initially checks whether the cookie has been created or not. If the cookie is created it displays the name and password stored in it.

Login.php

This page is showed when the cookie isn’t created. The user has to select the checkbox if he needs his details to be remembered.

Logout.php

This page deletes the cookie that has been created.

Now I haven’t concentrated much on the design aspect and this tutorial is to demonstrate how cookies are implemented. You may have to redo the entire code to implement it with your site. I hope this doesn’t bother you much.

index.php Code

$_COOKIE or $HTTP_COOKIE_VARS is a super global variable which is used to retrieve the data. Once the cookie is set I retrieve the data, which is stored in it. I have used “-“ as delimiter for each field i.e (name-password).

login.php Code

The above code authenticated the user and also if the user has opted to save the password and name we store them in a cookie. The password is encrypted using md5 and is concatenated with “-“ hyphen as field separator. Now the $cookie_data variable contains the concatenated string. The setcookie function is used to store the data into a cookie. The first argument is the cookie reference name (in this example “cookie_info”). The second argument is the data that is to be stored and the third would determine how long the cookie is valid. .

In the example the cookie lifetime is set to 1 hour. Now you must be wondering how? The time () function returns the current Unix time stamp. For example “1072724721” actually means Mon, 29 Dec 2003 19:05:21 UTC. Now lets add a 3600 to the Unix time stamp 1072724721 + 3600 = 1072728321 this is actually Mon, 29 Dec 2003 20:05:21 UTC. You need to spend bit of your time looking at mktime and time functions to understand this better. A cookie returns TRUE on successful creation. .

logout.php Code

Destroying a cookie is quite simple and you might also find that we again use the same function for this. Now you might see me subtracting 3600 what do I really mean by this? I am actually rewinding the clock and setting a old time to it. When I subtract 3600 it rewind my clock one hour before. So if you had created a cookie at 9 AM I will set it to 8 AM there by meaning the cookie has expired. I hope I didn’t sound complex. .

Conclusion

I guess the cookies scare has gone after reading this tutorial. Cookies are simple and it’s always a matter of time for you to understand. So right now all you need to practice a bit to get used to what you have learned. Post in your comments and suggestions for me to know what I sounded like.

If you like this post kindly subscribe to our RSS for free updates and articles delivered to you.

Related Posts

php-domain-information

How To Get Domain, Subdomain, TLD, CTLD & Path from URL In PHP

braintree-payment-gateway-integration-php

Integrating BrainTree Payment Gateway With PHP

How to create XML with PHP Mysql

How To Create XML With PHP MySQL

RBS WorldPay Integration With PHP

Integrating RBS WorldPay XML Direct Method with PHP

  • Pingback: Blogsvine()

  • Pingback: upnews.it()

  • in feb this year i started this http://www.wscoop.com its a digg style site but deicated to all aspects of web development and design

    But I need your help…

    I need links to web design and development, site , articles links… anything you think of…

    Please are you abel to help me make this into a great resource for developers and designers.

    You are more than welcome to promote your own sites, projects, comments and all… at the moment the posts go straight to the font page to it is good exposer and at least some sweet backlinks

  • Hello Paul,

    Thanks for dropping you comments. I have sent you an email please check and reply back.

  • ma gli snap nel codice non si potevano evitare?! :S

  • ma gli snap nel codice non si potevano evitare?! :S