Getting Started
Introduction
Perl IDEs
History
Advice
Tools
Mini-Tutorial
Tutorial
Code Snippets

Resources
Top Sites
More Tutorials
Books
Magazines
Articles
NewsLetters
Mailing Lists
NewsGroups
Forums
User Groups
Talk Shows
Blogs
Clothing

GBIC >> Perl >> Information Center Tutorials >> Cookies

Perl Information Center Tutorials - Cookies
These tutorials were written to help you get a quick, but thorough, understanding of Perl - the scope of the language as well as it's specific capabilities.

Beginners Built-In Functions     Advanced CGI Applications

Cookies
For security reasons browsers do not allow a web site to write information onto a users PC. The one exception is known as a cookie, which is a small text file that browsers will allow to be written.

When a server sends a web page to a browser it precedes the page content with a header of general information. If the header contains a cookie the browser will write the cookie to the user's PC. The browser manages all aspects of the cookie creation. Only the cookie content is provided by the server as part of the header.

It is also possible to use JavaScript to write a cookie. See my JavaScript Information Center for more information on creating cookies using JavaScript.

Creating Cookies Using Perl
In other sections of this tutorial you've already seen that Perl can provide header information when creating a web page (the "Content-type" line). In order to send a cookie to the browser, which the browser will store on the user's PC, an additional header line of text is required as follows:

     Set-Cookie: name1=value1,name2=value2,name3=value3,
     Content-type: text/html\n\n

The extra line defining a cookie precedes the "Content-type" line and consists of the text "Set-Cookie: " followed by name/value pairs separated by commas. In practice, the name/value pairs can consist of any text string, as long as the server knows how to decrypt the string. In the following example, the Perl script assumes that the name=value pair coding is used.

Reading Cookies Using Perl
When a browser send a request for a page to a web server it looks to see if a cookie for that page exists on the user's PC. If the cookie exists, it sent to the server along with the request for the web page.

The cookie can be found in the %ENV hash, as the value for the key "HTTP_COOKIE". The following Perl code will place the cookie name/value pairs into a hash called %Cookies.

     @pairs = split (',',$ENV{'HTTP_COOKIE'});
     foreach (@pairs) {
          ($key,$value)=split(/=/,$_);
          $Cookies{$key} = $value        # key/value pairs placed in %Cookies
     }

Reading Cookies on the User PC
Both Internet Explorer and Firefox provide the ability to read the cookies they have written. If you'd like a freeware standalone cookie reader then take a look at the Nirsoft site for their readers, IECookiesView and MozillaCookiesView.

If you have any suggestions for additions to these tutorials, please let me know.