Wednesday, 24 August 2016

PHP Cookies: How to Set Cookies & Get Cookies

Cookies don't have to be an essential part of a website but can provide some of the "little things" that can set your website apart from the rest. Cookies are small tidbits of information that you save on the client's computer so that you can access them next time they visit the website. Session ID's are also usually held in cookies.
So what are the most popular uses of cookies? They 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.

Setting the Cookie

Setting a cookie requires a key, a value, and the amount of time to allow the cookie to exist.
$name = 'Hemant Vishwakarma';
setcookie('name',$name,time() + (86400 * 7)); // 86400 = 1 day
Above, we set the user's first name equal to 'Hemant Vishwakarma' (this data would actually come from a form or database but for the sake of the example we'll use my name). Then, we set a cookie with the key of "name" with the value 'Hemant Vishwakarma', and program it to expire 7 days from now.

Getting the Cookie Values

Now that we've set our cookie, it's time to get the value pretend they left your site and are coming back two days later).
echo 'Hello '.($_COOKIE['name']!='' ? $_COOKIE['name'] : 'User'); // Hello Hemant Vishwakarma!
Above, we check to see if the cookie with 'name' as the key still exists. If so, we use their name; if not, we call them "User". Basic cookies are that easy!
PHP cookies can be set with more specific directives, including path, domain, secure, and httponly.
setcookie('name',$name,time() + (86400* 7),'/~sugar/','hemant.name',true,true);
This cookie is the same as above, but we're also telling the cookie to be applied towards the "~sugar" directory on the "hemant.name" domain. It is for use only on an SSL connection and it may not be used by JavaScript.
Some other things to know about cookies:
  • Although you set an expiration on the cookie, a user can delete cookies at any time.
  • Cookies can only be accessed by the browser that set them (Firefox and IE don't share them)
  • A user can turn cookies off in their browser.
  • Never assume a cookie exists.

PHP Cookies: How to Set Cookies & Get Cookies

No comments:

Post a Comment