+https://davidwalsh.name/php-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.
- 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.
$first_name = 'David'; setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day
Above, we set the user’s first name equal to ‘David’ (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 “first_name” with the value ‘David’, 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['first_name']!='' ? $_COOKIE['first_name'] : 'Guest'); // Hello David!
Above, we check to see if the cookie with ‘first_name’ as the key still exists. If so, we use their name; if not, we call them “Guest”. Basic cookies are that easy!
PHP cookies can be set with more specific directives, including path, domain, secure, and httponly.
setcookie('first_name',$first_name,time() + (86400* 7),'/~sugar/','davidwalsh.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 “davidwalsh.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.