Nearly every PHP application uses sessions.
This article takes a detailed look at implementing a secure session
management mechanism with PHP. Following a fundamental introduction to
HTTP, the challenge of maintaining state.
Cookies are just a basic aspect of PHP, but can be used in so many
things. From logging in and out a user on your website to keeping the
name of the skin they use on your website. Below I will explain how to
set (add) a cookie, delete one and then display/check one. I will first
show the PHP code and then explain it.
Add a Cookie
<?php
setcookie("username", $_POST[textfieldname],
time()+3600*60*24*14);
?>
Firstly the "username" part is the name of the cookie you want it to
have. Next up is simply the data you want that cookie set to, I have a
POST so if you login you would use a POST variable to get the data the
user put in as the username.
Delete a Cookie
<?php
setcookie("username", "", time()-3600*60*24*14);
?>
Yep the same PHP function. "username" as the name of the cookie,
make sure it is the same name as when it was first set. We set the next
value blank because we want to basically empty the cookie and then set
the time minus all that time we originally set it to, deleting the
cookie.
Displaying/Checking a Cookie
<?php
echo "Hello, welcome back ".$_COOKIE[username]."!";
?>
Pretty simple here, the COOKIE variable with the name of the cookie inside the brackets will display the data from that cookie.
<?php
if ($_COOKIE[username]) {
echo "Yes, I am logged in!";
} else {
echo "Nope, login please";
}
?>
As long as you understand if statements, then this is real simple.
The code above means if the COOKIE named "username" has value, then it
will say the "Yes, I am logged in!".
Conclusion
That about wraps it up. Above you can see how to add a cookie,
delete a cookie and then print/check a cookie. Logging in and other
things to expand moreso.
|