10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 1 ■ THE CGI MODULE 21Setting Multiple CookiesYou may find that one cookie isn’t sufficient for your application. In that case, you have twoprimary solutions:• You could simply set multiple cookies, each corresponding <strong>to</strong> a different setting or preference.This method works well for a few cookies, but remember that there’s a limit of20 cookies per domain.• If the application has a large number of cookies, a better solution is <strong>to</strong> create a sessionID, s<strong>to</strong>re that session ID in a database, and tie that database in<strong>to</strong> the settings and preferencesthat need <strong>to</strong> be s<strong>to</strong>red for the application.S<strong>to</strong>ring a session ID in a database has the advantage of giving your application virtuallyunlimited settings that it can s<strong>to</strong>re in the background, since only one cookie is sent <strong>to</strong> thebrowser. Also, since only one cookie is sent <strong>to</strong> the browser, you will save bandwidth, thusmaking the site seem quicker <strong>to</strong> the user. Granted, this is less important for LAN-basedapplications, but any savings of bandwidth are good savings. This section shows how <strong>to</strong> setand read multiple cookies using the CGI module.You can send multiple cookies <strong>to</strong> the browser by first creating the cookies, as you’ve done,and then passing the cookies as an array reference <strong>to</strong> the cookie() function. Listing 1-10shows an example.Listing 1-10. Sending Multiple Cookies Using CGI.pm#!/usr/bin/perl -Tuse strict;use CGI qw/:standard/;my $cookie1 = cookie(-name=>'testcookie',value=>'testcookievalue',expires=>'+7d');my $cookie2 = cookie(-name=>'secondcookie',value=>'secondcookievalue',➥expires=>'+1d');print header (-cookie=>[$cookie1,$cookie2]),start_html('CGI Cookie Test'),p("You've received a cookie\n"),end_html;exit;This code has only two differences from the code in Listing 1-9:my $cookie2 = cookie(-name=>'secondcookie',value=>'secondcookievalue',➥expires=>'+1d');print header (-cookie=>[$cookie1,$cookie2]),The first line creates a scalar containing a cookie with a name of secondcookie, a value ofsecondcookievalue, and an expiration of one day in<strong>to</strong> the future. Notice that the expirationof $cookie2 is different from that of the other cookie in this example.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!