Welcome to Cookies

Welcome to Cookies

welcome to cookies

https://www.insanevisions.com/tutorials/cookies.phps

Welcome to the first tutorial here at Insane Visions. I’m going to kick it off with a tutorial on cookies, PHP cookies.

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.

James

Hi there, I'm James, editor in chief at InsaneVisions.com and finance journalist. Feel free to message me on Twitter and Facebook. Make sure to subscribe to our mailing visit for the latest finance and tech news.
James