Click Now for a FREE E-Commerce Kit.
Click Now for a FREE E-Commerce Kit.


BUILDER.COM

Search for articles on BUILDER.COM:

 
 
 
 
 
 
 
 
 
 
The abc's of CGI - back to intro How To: use cookies with server-side includes
 
The hardest part of personalizing a Web page is maintaining state--tracking users as they click through your site. Web browsers and servers have no built-in mechanisms to keep tabs on and remember users as they flit from page to page.

But there is a solution. Because cookies allow Web builders to ask a user for personal information, store the data on their computers, and retrieve that knowledge when the user returns, they are the most common way to track visitors.

To use a cookie, a script must first retrieve the necessary information. The following example is a simple, reusable script using server-side includes (SSIs) that we can invoke within an existing HTML page to retrieve the information stored by the personalization example. Remember to save it as cookie.pl:

what is CGI?
when to use CGI
hosting issues
how to:
process a form
use cookies to personalize Web pages
use cookies with server-side includes
create a simple guestbook
add a page-visit counter
troubleshooting

#!/usr/bin/perl

foreach (split(/; /, $ENV{'HTTP_COOKIE'})) {
 ($chip,$value) = split(/=/);
 $cookie{$chip} = $value;
 }

print "$cookie{$ARGV[0]}";
By using SSIs in your existing HTML document, you can retrieve the cookies and place them in your page when needed, as demonstrated in the example below. But before you do so, make sure that your server is configured to use SSIs. Also, check to see that the SSI uses the right path from the server's root, not the URL or document root:
<html>
<head><title>hello,
<!--#exec cmd="/real/path/to/cookie.pl name"-->
</title></head>
<body bgcolor="<!--#exec
 cmd="/real/path/to/cookie.pl color"-->">

Welcome back,
<!--#exec cmd="/real/path/to/cookie.pl name"-->

<p>

I have never been to
<!--#exec cmd="/real/path/to/cookie.pl city"-->,
but I'd love to go there someday.

</body>
</html>
screen shot
This page is generated by retrieving the cookies that were set in the previous exercise.

In the text above, the portion of code that looks like an HTML comment is actually an SSI, which we use to send a prebuilt page to the user. When the page is requested, the server parses the document and executes the program called by the SSI--in this case, the cookie.pl script we created earlier. Since we've already appended the name of the cookie to the SSI, we can pass it to the script. Now, when a user loads this page, the CGI checks to see if they have our cookie. If they do, the user will be presented with a personalized page.

See the complete Perl code.

how to: use cookies to personalize Web pages how to: create a simple guest book


 

Click Now for a FREE E-Commerce Kit.
Click Now for a FREE E-Commerce Kit.

Back to top  Go to the BUILDER.COM home page.

  Copyright © 1995-98 CNET, Inc. All rights reserved. Privacy policy.