PHP Cookies
Cookies are just like sessions used for storing data that needs to be remembered and accessed from different files. However, unlike sessions, cookies are saved on the user’s browser ( client-sided ). They can be stored in there for any period unlike sessions ( which are saved for a constant ‘session period’ ). However, they are dependent of the user’s browser and browser settings. If the user chooses to turn off cookies or if the browser simply does not allow cookies, they will not work. But none the less cookies can be quite useful and are used a lot. This is especially because they can save data for ‘unlimited’ time. Just like sessions, each cookie is a sub-variable of an array: $_COOKIES. To create a cookie variable, you simply create a sub-variable of this array. However, this time a function is needed to do so: the function set_cookie.
full function usage
set_cookie( name, value, expire, path, domain, secure, httponly );
basic function usage
set_cookie( name, value, expire);
The arguments of the function are quite a lot, however you usually only need the name, value and expiration data to be set. In fact, only the name must be given for the function to work. The other arguments are optional.
You can as well access any of your cookie variables on any page of your website. They do not need to be ‘activated’ or something, like for sessions, as they’re dependent of the browser. Al though, unlike sessions, cookies need to be created at the very TOP of the page.
Example1.php
<?php set_cookie( “username”, “Admin”); // now the cookie can be used anywhere in any file // ... rest of your webpage ... ?>
Example2.php
<?php
if(isset($_COOKIES[‘username’]) && !empty($_COOKIES[‘username’])) {
echo “Welcome back, “.$_COOKIES[‘username’];
}else{
echo “You are not logged in.”;
}
?>
You cannot use the set_cookie function after any graphical content ( HTML output ). However you can of course USE your cookies anywhere in your scripts, though they need to be created at the top of a script. For the rest, it can be used just the same way as sessions.