Cookies and You

Cookies and You

Posted By: borednerd on Mar 06, 2005

Learn about cookies and where to use them

First of all, you must define what you want to do with your script.
Cookies, are used mostly for login systems, and are very similar to Sessions but are different in some way or another.

A Session or Cookie is basically said to be a document on your (YOUR) computer with which you would store information. Cookies such as on this very forum. Somewhere on your computer there is a file that has information that was put and made by this forum. The forum recognizes this cookie, and tells you that you are logged in. Basically, its that "remember me" feature.

A Cookie and Session are very much alike in that they store information. But a cookie can last for as long as you set it, and a session will terminate once the browser is closed.

When first beginning with cookies, you should note that a cookie is part of the header information, and should be sent before any other content to the servers.

Bad Cookie
HTML Code:
<HTML>
<HEAD>
<TITLE>Bad Cookie</TITLE>
<BODY>
<?
setcookie("test", "ok", "", "/", "yourdomain.com", 0);
?>

<H1>Bad Cookie</H1>

</BODY>
</HTML>
Now as you can see the cookie was not the first thing sent, the HTML was sent first, and then the cookie. You will recieve a secondary parse error looking like:
Code:
Warning: headers already sent in /path/to/badcookie.php
Setting Cookies

To set a cookie, use the setcookie() function to set one cookie at a time. You must remember that there are six
  • Name. Holds the name of the variable that is kept in the global $_COOKIE and is accessible in scripts included
  • Value. The value of the variable passed in the name
  • Expiration. Sets a specific time at which th ecookie is no longer accessible and destroyed. Cookies wihtout a specific expiration time will expire when the browser is closed.
  • Path. Determines for which directories the cookie is valid. If a single slash is the value, the cookie is valid for all files and directories in the server. If a specific directory is named, this cookie is valid for that directory only.
  • Domain. Cookies are valid for only the host and domain that set them. If no domain is specified, the default value is the host name of the server that generated the cookie. (Domain value must have at least two periods in the string in order to be valid.
  • Security. If the value is 1, the cookie will only be transmitted via HTTPS (https://yourdomain.com) in other words, a secure web server.

The next line is an example of setting a cookie. In this example, we will record the time at which the user visited the website.

So first, open the PHP editor or notepad, begin a php block (<?php ?>), and using the setcookie() function, we set our cookie.

PHP Code:
setcookie("time_visited"date('m/D/Y'), time()+14400"/"".yourdomain.com"0); 
Basically, what we just said is, "If this page is visited, create a file with the variable "time_visited", and set it equal to the date at which he visited (02/22/05 for example). Let it expire 14400 seconds from NOW(time()) which is in essence, 4 hours. Let it work on any folder, on "yourdomain.com", and it is not secure.

The basic setcookie use is:

PHP Code:
setcookie(VARIABLE NAMEVARIABLE VALUEEXPIRATION DATEACCESS PATHDOMAINSECURE); 
From now on, you can call variables et by using the $_COOKIE global variable. So saying that we made that cookie variable, "time_visited", we can call the value using the PHP:
PHP Code:
echo "You visited here at " $_COOKIE['time_visited']; 
Which is in essence, $_COOKIE['variable_name'].

Counting Time
To have cookies last longer, use the time() function, which is the current time at which the script is accessed, and add # of seconds to it to project the time.
So:
  1. time()+60 - One minute from the current time
  2. time()+900 - 15 minutes from the current time
  3. time()+1800 - 30 minutes from the current time
  4. time()+3600 One hour from the current time
  5. time()+1400 - Four hours from the current time
  6. time()+43200 - 12 hours from the current time
  7. time()+86400 - 24 hours from the current time
And basically, you can even set a function to output X days to make it easier on yourself.
PHP Code:
function DaysToSeconds($strDays)
{
$str24Hour time()+86400;
$strReturn $str24Hour $strDays;
return 
$strReturn;

And then you would do:
PHP Code:
#If you want lets say, 3 days:
$3Days DaysToSeconds(3);
#$3Days = time()+259200; 
And you get the same variable.

Setting a Test Cookie
Now that we have many of the functions is place, we can start fooling around and having some fun with cookies!

For a test, try this:
PHP Code:
$cookie_name "test_cookie";
$cookie_value "test string!";
$cookie_expire DaysToSeconds(1); #One Day
$cookie_domain "yourdomain.com"#if you are on localhost, 127.0.0.1
#then lets use the setcookie function to create the cookie
setcookie($cookie_name$cookie_value$cookie_expire"/"$cookie_domain0); 
Then to embed it in html, just call the variables by using $_COOKIE['test_cookie'];.

Usefullness of Cookies
Now that we've learned how to set up cookies, we can try setting up a hit counter (which counts how many times a single user has been to the page)
PHP Code:
#user hit counter:
#set the cookie
setcookie("user_hits"0DaysToSeconds(10), "/""yourdomain.com"0);
#then set up an if...else clause to add values to hits
if($_COOKIE['user_hits'] > 0) {
#if the user has been here more than once, add one more time
#$_COOKIE['user_hits']  = $_COOKIE['user_hits'] + 1;
$_COOKIE['user_hits']++;
} else {
#if the user has been here not at all, set it equal to one

$_COOKIE['user_hits'] = 1;
}
echo 
"You have been here " $_COOKIE['user_hits'] . "time(s)"
Any questions, comments, feel free to PM me, or check for more PHP/MySQL tutorials here and at GameIllusion. Thanks,
Brian Isaacs
  • Comment on this tutorial
  • View the Printable Version

Posted On: Mar 06, 2005

Hits: 21804 - Unique: 16256

Advertise Here!

Quick Tutorial Search

VDC - Visual Design Core on Facebook

Our Popular Tutorials

Signature Backgrounds

Abstract Airbrushing

Rusty Metal Plate

Abstract Wave Technique

Cinema 4d Materials Tutorial

Abstract Renders in Cinema 4d

Photoshop logo to Cinema 4d logo

Dark Art Guide