Miscellaneous Web Gizmos

Setting a cookie on an e-mail newsletter

Setting a cookie on a pdf

Setting a Cookie on an Image

This is a low-tech method of keeping track of your HTML e-mail readership. There's no doubt a more robust solution, but for many purposes this will give you at least some idea of what people are even opening your message.

Instead of a direct link to an image file, your e-mail has a link to a cgi script. The query string carries three semi-colon separated parameters, a unique user ID, the path to the image we want to display, and the name to give to the set cookie.

<img src="/root/cgi/img.pl? <userid>;<path-to-image>;<cookie-name>">

The img.pl script summons up the cgi cookie module, and splits apart the three parameters. It then builds the cookie and sets it in the first line of the response header. The second line sets the content-type. You might as well stick with a gif; we just pointed to an invisible 1-pixel graphic. If a user's filters block the image link (many corporate e-mail systems will), it doesn't screw up the layout if that is missing the way a missing logo would.

use CGI::Cookie; my $input = $ENV{'QUERY_STRING'}; $input =~ /(\d*);([^;]*);(\w*)/; my $id = $1; my $path = $2; my $cookie = $3; my $c = new CGI::Cookie (-name => $cookie, -value => $id, -domain => '.yourdomain.com', -path => '/', -expires => '+3M'); print "Set-Cookie: $c\n"; print "Content-type:image/gif\n\n"; open (FILE, "/server/root/$path") || die "can't open, $!"; binmode FILE; binmode STDOUT; while ( <FILE> ) { print } close FILE;

Once the response header is sent, the script actually opens the file of the image, and delivers it the client. As far as the browser is concerned, it doesn't care if the server is sending the file or the script is; it's the same data stream.

Note that a redirect doesn't work here, because the cookie needs to be in the response header. Also note, the image can be anywhere on the box, it doesn't have to be in the published directory. You can use this to secure images from casual browsing on your web site, too. Pull in the HTTP_REFERER environmental variable and make sure it's what you want it to be.