Lesson 13: Cookies - TOP10

Lesson 13: Cookies

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.  

How to Create a Cookie? 

The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the <html> tag. Syntax:  setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )




Tips and Notes  
Tip: The value of a cookie named "user" can be accessed by $HTTP_COOKIE_VARS["user"] or by $_COOKIE["user"].  
Note: The value of the cookie will automatically be URL encoded when you send the cookie (and automatically decoded when received). If you don't want this, you can use setrawcookie() instead.   
Example1: In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also specify that the cookie should expire after one hour:  <?php setcookie("user", "Alex Porter", time()+3600); ?>  
Example2: You can also set the expiration time of the cookie in another way. It may be easier than using seconds.  <?php $expire=time()+60*60*24*30; setcookie("user", "Alex Porter", $expire); ?> In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).  
How to Retrieve a Cookie Value? The PHP $_COOKIE variable is used to retrieve a cookie value.  
In the example below, we retrieve the value of the cookie named "user" and display it on a page: <?php // Print a cookie echo $_COOKIE["user"];  
// A way to view all cookies print_r($_COOKIE); 
?>  
In the following example we use the isset() function to find out if a cookie has been set:  <html> <body>  

<?php if (isset($_COOKIE["user"]))   echo "Welcome " . $_COOKIE["user"] . "!<br />"; else   echo "Welcome guest!<br />"; ?>  
</body> </html>  
How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past.  
Example:  <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>  
Create an array cookie  <?php setcookie("cookie[three]","cookiethree"); setcookie("cookie[two]","cookietwo"); setcookie("cookie[one]","cookieone");  
// print cookies (after reloading page) if (isset($_COOKIE["cookie"]))   {   foreach ($_COOKIE["cookie"] as $name => $value)     {     echo "$name : $value <br />";     }   } ?>  Output: three : cookiethree two : cookietwo one : cookieone   





Previous
Next Post »