Set and retrieve a cookie using Perl and CGI

There are multiple parameters which can be set when creating a cookie. This does not apply to only Perl and CGI but to all other development environments. The only required parameter we need to set cookie with is a cookie name.

Other parameter which should also be mentioned is a cookie expiry date. Some browsers would not even accept a cookie with no expiry date but mostly cookies with no expiration date are accepted and are saved for a current session only.

To create a cookie which will be saved for more than a single session a cookie expiration must be set. Use the following code Perl/CGI to create a cookie with:

  • Name: CGI-PERL-COOKIE-EXAMPLE
  • Value: cookie.linuxconfig.org
  • Expiry Date: 1 year from now
#!/usr/bin/perl -T
use strict;

use CGI qw/:standard/;

my $cookie = cookie(
	-name=>'CGI-PERL-COOKIE-EXAMPLE',

	value=>'cookie.linuxconfig.org',
	-expires=>'+1y');
print header (-cookie=>$cookie),

	start_html('CGI Cookie with Exipire Date'),
	p("Cookie had been saved !\n"),
end_html;

exit;

Save your code into /usr/lib/cgi-bin/expiry-date-cookie.cgi and make it executable:

# chmod 755 /usr/lib/cgi-bin/expiry-date-cookie.cgi

If your browser allows you to see all stored cookies you should be able to find your own cookie. Here is a screenshot of my cookie when using firefox browser.

Perl CGI cookie with expiry date

To retrieve your cookie with Perl/CGI use a following code. Make sure that you set correct cookie name:

#!/usr/bin/perl -T
use strict;

use CGI qw/:standard/;
my $retrieve_cookie = cookie('CGI-PERL-COOKIE-EXAMPLE');

print header,
start_html,
p("Cookie value is $retrieve_cookie\n"),
end_html;
exit;

The following code uses same principles of creating a cookies however on larger scale. When creating a cookies we need to keep in mind that there is a limitation of maximum 20 cookies per domain. Use a following code to create multiple cookies simultaneously. The code first creates a scalar variable to hold a cookies definitions and then we print a header with both cookies in form of array.

#!/usr/bin/perl -T
use strict;

use CGI qw/:standard/;
my $cookie1 = cookie(-name=>'cookie_one',value=>'value1',expires=>'+1d');

my $cookie2 = cookie(-name=>'cookie_two',value=>'value2',expires=>'+10y');

print header (-cookie=>[$cookie1,$cookie2]),
start_html('CGI Multiple Cookie Example'),

p("Cookies received!\n"),
end_html;
exit;

Similarly the code below retrieves multiple cookies at once:

#!/usr/bin/perl -T
use strict;

use CGI qw/:standard/;
my $retrieve_cookie1 = cookie('cookie_one');

my $retrieve_cookie2 = cookie('cookie_two');
print header,
start_html,
p("COOKIE_ONE Value: $retrieve_cookie1 \n"),

p("COOKIE_TWO Value: $retrieve_cookie2 \n"),
end_html;
exit;