Passing Variables – PHP Cookies

Before we set some cookies, let's look at the flow of messages and responses between your computer, and the server, where the web pages are stored. When you click on a link to go to a web site, your browser sends a "HTTP Header" request to the server for that web page. The Header message is variable in length and can get lengthy. The browser sends the HTTP Header, then waits for the server to send a "response header," followed by the web page. How does the server know that the browser's Header message is complete so it can respond? A blank line is sent at the end of the HTTP Header. The server when seeing the blank line responds with a "response header," before passing the page.

Why am I going through this? Because the event that passes the communication baton from browser to server, and back again is a "blank line." When you pass a cookie to a browser, it is attached to the server's "response header", but if a blank line shows up in the web page, before you tell the server to attach the cookie to the response header, you'll get an error message, something like, "Warning cannot modify header information - headers already sent..." In other words, your command came late, the headers already gone. This can drive you nuts trying to figure out where the bug is in your code, if your not aware of what's happening. The first thing you want to avoid is a blank line, or even a space at the top of the file before the PHP start tag.

The first step in setting a cookie is to tell the server to attach the cookie to its response header. This is done at the very top of the web page, before any blank lines, or "HTML" or "head" tags, with PHP's "setcookie" function, like this:

<?php
setcookie( 'message_1', 'I am loaded and ready for bear');
?>

The "setcookie" function can take up to six parameters:

1. "Name", the name of the cookie, a string, in this case: 'message_1' ;

2. "Value", the value of the cookie, can be a string or number, in this case: 'I am loaded and ready for bear' ;

3. "Expire", when the cookie should expire on the user's browser. This is expressed in seconds, in linux system time based on seconds since January 1, 1970. I suggest you use a PHP time function, and add to it the number of seconds you'd like the cookie to be active in the browser, or use the browser default, since I'm using Firefox, the browser default is 90 days;

4. "Path", the path on the server where the cookie will be made available. There's a lot of files on the server, default is the current path;

5. "Domain", the domain or url for which the cookie will be available. If you have multiple servers serving pages, on which server will cookie information be made available. The default is the current server.;

6. "Secure", if you only want the cookie to be sent over a secure connection, like "https://", set it to "1," if it's to be secured, the default is "0," not secure.

Cookies exist in pairs, a name of the cookie, and its value. The other four parameters are usually not sent, the defaults are used. Normally, only two parameters are passed, name and value.

When your browser receives the cookie from the server it stores it in a set file location on your computer, depending on the browser. When you access that web site again, the browser, if there is a cookie available for that web site, attaches to to the HTTP Header it sends to the server. Cookies are a two-step process, you send it first to set the cookie, and then to get the cookie back you have to ask for the page again.

Ok, we've set the cookie in the first response header from the server, how do we get the cookie back from the browser. Well, the cookie, when it comes back, is attached to the HTTP Header, how do we read it? Assuming you've refreshed your browser, or asked for the page again. Here's a block of code to do just that,

// Always check to see if the cookie exists,
// or was not deleted by the user
if (isset($_COOKIE['message_1'])){

   echo "The cookie is loaded: " . $_COOKIE['message_1'] ;
}

If the cookie exists and is set, this will echo: "The cookie is loaded: I am loaded and ready for bear"

You also can set cookies in an array. Here's an example with the cookie's expiration time set to 10 days :

setcookie ( "myarray[one]" , "My " , time()+ 60*60*24+10 );
setcookie ( "myarray[two])" , "Funny " , time()+ 60*60*24+10 );
setcookie ( "myarray[three]" , "Valentine ", time()+ 60*60*24+10 );

To retrieve this array, we use a loop thus:

if ( isset($_COOKIE['myarray']) ) {
   foreach ( $_COOKIE['myarray'] as $note ) {
      echo $note ;
   }
}

And the output is: "My Funny Valentine". And finally you can change a cookies value by calling setcookie() again, or delete the cookie by specifying a time in the past, thus: setcookie( "x", "" , time() - 3600 ) will delete the cookie.

I mentioned cookies are public. Although, you can not look at them directly with a regular text editor, like notepad, and they can be encrypted, there are cookie management editors you can download to read cookies, and there are TCP/IP tools that you can use to watch the traffic go back and forth to a web site including the cookies with their names and values. Cookies can be useful, just be careful how you use them, and what information you store in them.

Comments

Passing Variables – PHP Cookies — 2 Comments

  1. Thanx a lot daleV
    Around two weeks i was struggling in set cookies and receiving the “header already sent” error.
    when i read this post i fond my solution..actually on page load a cookies will set..i was passing php textfield variable value to setcookie function but it was not taking value because on same page setcookie function is on the top..when a page load it set the cookie if it fond value otherwise no. so when i put this setcookie function to next page and with a starting blank line at to and provide the posted value from previous page then it ran absolutely that i want.

    Thanx aging daleV