We can interact with our user and user browsers using cookies.
Cookies are a way for a server to store information on the user’s machine. This is one way that a site can remember or track a user over the course of a visit. Think of a cookie as being like a name tag: you tell the server your name and it gives you a sticker to wear. Then it can know who you are by referring back to that name tag.
Our web server can make a request to users’ web browser to send back a cookie. Cookies are going to be accessed in same way $_GET and $_POST work.
How to set cookie?
Setting cookies going to take following format.
$name is name of cookie. $value is cookie’s value and $expire sets cookie expiry time as unix timstamp. $name, $value and $expire are essential parameters for setting cookies.
setcookie needs to happen before any HTML is sent that includes white space such as single space, a tab.
Lets try above code in localhost.
Setting cookie did not echo anything back all it did was set cookie. We can check in to see whether it is really set.
In Firefox, go to Tools >> Options from menubar.
You will see a dialog box with many tabs like General, Tabs, Content, Applications, Privacy, Security, Sync. Click ‘Privacy‘ tab.
Go to ‘History’ section in Privacy tab and select value ‘Use custom settings for history‘ from dropdown next to ‘Firefox will’.
Click button ‘Show Cookies’.
Search for phrase ‘test’ And you will see your cookie. Also you can see its value mentioned as ‘Content: 45‘ in above screen. Notice we can see the value of cookie. The value may not be meaningful to user. But as a developer we should keep in mind that we expose this value to our users and its possible that hacker might be able to use that information to manipulate cookie to do something malicious. For example, we might be storing userId in cookie. So hacker might use this value to pull out some more information about user.
Reading Cookie using PHP:
To read cookie we have to call cookie superglobal $_COOKIE and tell it that we want ‘test’ cookie. And then simply echo it to browser.
How to remove cookies:
This can be done in two ways.
1. We can set cookie value to be blank or nothing.
2. We can set its expiration date to some date or time past.
Lets see how we can set expiration date so that cookie can last one week ago. Also we can set cookies value to 0. So combination of two will make sure that we get rid of cookie.
Lets try read back test cookie. It should say cookie does not exits.