Home arrow PHP arrow Page 4 - Website Database Basics With PHP and MySQL

Using cookies to identify and track visitors - PHP

The World Wide Web (WWW) does only one thing - provide information. If you have information about something, you can share it with the world by building a website. As your website grows you may run into two problems: Your website has so much information that visitors can't quickly find what they want and visitors want to give you information. Both of these problems can be solved by building a database on a website. This introductory article shows you how to do this using basic PHP-MySQL interaction.

TABLE OF CONTENTS:
  1. Website Database Basics With PHP and MySQL
  2. HTML talks to PHP talks to MySQL
  3. Verifying form data
  4. Using cookies to identify and track visitors
  5. Weird SQL: What The Books Don't Tell You
  6. Checkboxes and other HTML form processing
By: Thomas Kehoe
Rating: starstarstarstarstar / 100
January 11, 2000

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
By assigning a "cookie," your website can identify and track a visitor across webpages. A cookie is a set of data stored in the visitor's browser. We'll look at how to assign a unique customer ID number to each visitor and set this as a cookie. Your visitors can then repeatedly access your database, with their data always going to their own record.
  1. Viewing your browser's cookies
  2. Setting cookies
  3. Cookies are variables
  4. Setting a cookie from a database lookup
  5. Receiving a cookie
Note that the on-line PHP manual describes cookies in the HTTP functions chapter, not in the chapter titled Cookies.

Viewing your browser's cookies

Take a look at the cookies stored by your browser. With Microsoft Internet Explorer, go to Edit...Preferences...Receiving Files...Cookies. Alternatively, you can search your hard drive for a file called cookies.txt. You should see a list of servers, e.g., amazon.com. Choose a cookie and click View. You'll see six properties set by the website that created the cookie, plus whether the cookie is enabled. For example:

Cookie Properties
Name:ubid-main
Server:amazon.com
Path:/
Value:012-3456789-0123456
Expires:Tue, Jan 1, 2036 8:00 AM GMT
Secure:No
Status:Enabled

When your browser pulls a webpage from the Internet, it compares the domain name of the webpage to the domain names in its cookie list. If there's a domain name match, then the browser sends the matching cookie(s) to the server. The server then can create a custom webpage using data from that cookie.

For example, when I connect to Amazon.com, my browser sends four cookies to Amazon before Amazon sends me the first webpage. ubid-main is the cookie that identifies me. Amazon looks up the Value: number in its database, matches it to my name, and creates a custom webpage that begins:

Season's greetings, Thomas D Kehoe. (If you're not Thomas D Kehoe, click here.)

Setting cookies

Cookies have to be set before the server sends anything to the browser. E.g., Amazon had to identify me before it created a custom webpage welcoming me. To accomplish this, cookies must be set before the <HEAD> HTML tag. Actually, the cookie must be set before the <HTML> tag, as the following example shows:



<?php setcookie("CookieID", $USERID); ?> <HTML> <BODY> </BODY> </HTML>



If you get the error Warning: Oops, php3_SetCookie called after header has been sent, then you sent the <HTML> tag before setting the cookie. The error message is confusing because the above example doesn't send any header information using the <HEAD> tag.

The setcookie function takes up to six arguments, separated by commas:

  1. The cookie name, a string, e.g., "CookieID". Semi-colons, commas, and white spaces are not allowed. The cookie name is required (all other arguments are optional). If only the cookie name is included, and no other arguments, the cookie will be deleted.
  2. The cookie value or contents, a string, e.g. $USERID. To skip, use an empty string (""). Slashes apparently are not allowed.
  3. The time the cookie expires, an integer. If this is omitted (or filled with a zero) the cookie will expire when the session ends. The time can be an absolute time, in the format DD-Mon-YY HH:MM:SS, e.g., "Wed, 24-Nov-99 08:26:00". Or, more usefully, the date can be in relative time. This is done with the UNIX time() or mktime functions. For example, time()+3600 makes the cookie expire in one hour. Some older browsers don't handle cookies properly if the time argument is omitted.
  4. The UNIX directory path. This is used to identify cookies beyond the domain name identification. The path "/" is the same as omitting this argument except that some browsers don't handle cookies correctly if the path is not set, so use the slash instead of omitting this argument. Note that Netscape's cookie specification puts domain before path, but PHP puts path before domain.
  5. The domain name of the server, for matching cookies. If omitted, the domain name is taken from the webpage the cookie is sent from. Note that you must put a period (.) before the domain name, e.g., ".friendshipcenter.com". Cookies are rejected unless they have at least two periods (for the domains com, edu, net, org, gov, mil, and int; all other domains require at least three periods).
  6. secure is set by an integer. 1 means that the cookie can only be sent via a secure network. 0 (or omitting this argument) allows the cookie to go over unsecured networks.
There are many bugs in older browsers that screw up cookies. See the
reader's notes in the on-line PHP manual for details and fixes.

Cookies are variables

When a PHP script receives a cookie from client browser, it's automatically converted into a variable. E.g., a cookie named CookieID becomes the variable $CookieID.

To see a cookie, print the variable:



print $CookieID;



Alternative means to the same end

Cookies are stored in the array HTTP_COOKIE_VARS. You can print a cookie's value with:



print $HTTP_COOKIE_VARS[CookieID];



Setting a cookie from a database lookup

Going back to our webpage submitform.php, which inserted the visitor's name into our database, let's add code to look up the USERID number our database automatically assigns to each submitted name, and then send a cookie to the visitor's browser with the value set as the USERID number.

But first, let's look at AUTO_INCREMENT. MySQL can be set to assign a number to each new record, starting with "1". The next inserted record gets "2", the next is "3", etc. You can add such a column, in this case called USERID, with this bit of SQL:



ALTER TABLE dbname ADD COLUMN USERID INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT;



The new field USERID is set as an 11-digit integer (allowing nearly 100 billion records); the field is not allowed to be empty (NOT NULL), the database is indexed by this field (PRIMARY KEY), and, lastly, AUTO_INCREMENT is set.

To set a cookie in the visitor's browser after he or she inserts his name into your database, with the value of the cookie taken from the USERID, you could do this:



<?php mysql_connect (localhost, username, password); mysql_select_db (dbname); mysql_query ("INSERT INTO tablename (first_name, last_name) VALUES ('$first_name', '$last_name') "); setcookie("CookieID", mysql_insert_id(), time()+94608000, "/"); /* expires in 3 years */ ?>



The PHP function mysql_insert_id() returns the AUTO_INCREMENT number assigned in the last INSERT query. No arguments are required, although you can put in a variable which has been assigned the value of the mysql_query.

Try it out and then look at your browser's cookie list. You should see "CookieID" listed. Use your terminal emulator to view the contents of your MySQL table and see that the USERID of the last submission is the same as the value of the cookie listed in your browser.


Receiving a cookie

Let's write a PHP script for a webpage like Amazon.com. First, the PHP script checks if the client's browser has sent a cookie. If so, the visitor's name is displayed. If no cookie is found, a form is displayed for the visitor to submit their name, which is then added to the database and a cookie is set in the client's browser.

First, let's create a webpage that displays the visitor's cookie:



<?php print $CookieID; ?>



Save this script as cookiepage.php. If you save this to your UNIX server, then open the webpage after running the last version of submitform.php, you should get the value of your cookie. You can check it against your browser's cookie list and your MySQL database.

Now let's make cookiepage.php welcome me by name:



<?php mysql_connect (localhost, username, password); mysql_select_db (dbname); $selectresult = mysql_query ("SELECT * FROM tablename WHERE USERID = '$CookieID' "); $row = mysql_fetch_array($selectresult); echo "Welcome ", $row[first_name], "!"; ?>


 
 
>>> More PHP Articles          >>> More By Thomas Kehoe
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: