Cookies & PerlCookies are a mechanism to save state information in a browser. A web application can send one or more cookies to the browser accessing the application. The browser will then bring the cookie(s) back to the application on subsequent accesses, until the cookie(s) expires. Each cookie has a name and a value (similar to named parameters in the QUERY_STRING). This mini tutorial shows you how to: Creating and sending cookiesUse the method called
Although this creates the cookie, it is not sent to the browser unless you explicitly do so. Cookies must be sent in the HTTP response header generated by your application. You can use the following statement to send the above cookie to the brower:
(Note: As always you should ensure that the header is printed before any other text.) If you have multiple cookies, create all of them and send them in the header as a list. Here is an example:
If you have an array of cookies, make sure you send a reference to the
array of cookies in the header method. For example, if you have
You can also modify a cookie value the same way you set a cookie. For
example, to change the value of the cookie whose name is
Retrieving cookiesWhen a browser brings back a cookie that has previously been set you
can find its value using the
If the cookie named firstname does not exist, then
Session cookies vs persistent cookiesBy default new cookies are session cookies. That is, these cookies expire whenever the all browser windows on the client are closed. If you want a cookie to survive beyond this you need to make them persistent. This involves simply setting the expiry time of a cookie. For example, if you want to cookie to persist until January 1, 2010, you would perhaps try something like this:
You can also use shortcuts like:
Use negative to go back in time (to make a cookie expire immediately). You might want to look at a simple CGI perl program that demonstrates cookies. |