Wednesday, December 12, 2012

Cookies Are Good - PHP For Beginners Lesson 10


Cookies (not just for your sweet tooth)
By Stephon Unomon
Google + 

 

You are hopefully familiar with Cookies - you get them almost anytime you visit a website. Cookies allow you to store information about your visitor’s session on their computer. 

 

One of the most common uses of cookies is to store usernames. That way when a viewer returns to your site, they don’t have to log in each time they visit.

 

You can create cookies in PHP with:

 

<?php

setcookie(name, value, expiration);

?>

There are 3 requirements when setting a cookie:

 

  Name:  This is where you set the name of your cookie so you can retrieve it later.

  Value:  The value you wish to store in your cookie.  Some common values are usernames or date last visited.

  Expiration:  When your cookie will be deleted from the user’s computer.  If you do not set an expiration date, the cookie will be deleted when the viewer closes their browser!

 

Getting information from a cookie is just about as easy as setting one. Remember the “ISSET” stuff a few minutes ago? PHP gets cookie data in a similar way, by creating an associative array (Yes, again!) to store your retrieved cookie data...using the $_COOKIE variable.

The array key is what you named the variable when it was set (so, obviously you can set any number of cookies!) So...

 

<?php

if(isset($_COOKIE['username'])){ // If there’s a cookie...

$username = $_COOKIE['username']; // set the variable...

echo "Welcome back, $username."; // and show the data in the cookie...

} else {

echo "No username was found. Sorry!";} // or show this if there wasn’t one.

?>

 

And, FYI...Cookies are stored as small text files on your computer (in case you did not know!)

 

Our next lesson will be...one of the most useful functions of PHP... find out tommorow!

PHP Tree View

No comments:

Post a Comment