HTTP Cookie Library FAQ

Frequently asked questions about HTTP cookies and persistent client state.

Q1: How do I use the Cookie Library?

To use the Cookie Library in your CGI scripts:

  1. Include the library at the top of your script:
    require "cookielib.pl";
  2. Set a cookie:
    &SetCookie("cookie_name", "value", "30d");
  3. Get a cookie:
    $value = &GetCookie("cookie_name");
  4. Delete a cookie:
    &DeleteCookie("cookie_name");

Q2: How do I set cookie expiration time?

The expiration time is the third parameter in SetCookie(). Use these formats:

FormatExampleResult
Minutes"30m"Expires in 30 minutes
Hours"2h"Expires in 2 hours
Days"7d"Expires in 7 days
Months"1M"Expires in 1 month
Years"1y"Expires in 1 year

Examples:

# Session cookie (no expiration)
&SetCookie("session", $id, "");

# 30-day cookie
&SetCookie("remember", "yes", "30d");

# 1-year cookie
&SetCookie("prefs", $data, "1y");

Q3: How do I set the cookie path and domain?

Use the extended SetCookieExt() function to set path and domain:

&SetCookieExt($name, $value, $expire, $path, $domain, $secure);

Parameters:

  • $path: URL path where cookie is valid (default: "/")
  • $domain: Domain for the cookie (default: current domain)
  • $secure: Set to 1 for HTTPS only

Examples:

# Cookie for entire site
&SetCookieExt("user", $id, "30d", "/", "", 0);

# Cookie for /admin/ section only
&SetCookieExt("admin", $token, "1h", "/admin/", "", 1);

# Cookie for all subdomains
&SetCookieExt("session", $data, "1d", "/", ".example.com", 0);
Back to FAQ