10.2. Using CookiesThe setcookie( ) call needs to be before the HTML form because of the way the web works. HTTP operates by sending all "header" information before it sends "body" information. In the header, it sends things like server type (e.g., "Apache"), page size (e.g., "29019 bytes"), and other important data. In the body, it sends the actual HTML you see on the screen. HTTP works in such a way that header data cannot come after body datayou must send all your header data before you send any body data at all. Cookies come into the category of header data. When you place a cookie using setcookie( ), your web server adds a line in your header data for that cookie. If you try and send a cookie after you have started sending HTML, PHP will flag serious errors and the cookie will not get placed. There are two ways to correct this:
The setcookie( ) function itself takes three main parameters: the name of the cookie, the value of the cookie, and the date the cookie should expire. For example: setcookie("Name", $_POST['Name'], time( ) + 31536000);
In the example code, setcookie( ) sets a cookie called Name to the value set in a form element called Name. It uses time( ) + 31536000 as its third parameter, which is equal to the current time in seconds plus the number of seconds in a year, so that the cookie is set to expire one year from the time it was set. Once set, the Name cookie will be sent with every subsequent page request, and PHP will make it available in $_COOKIE. Users can clear their cookies manually, either by using a special option in their web browser or just by deleting files. The last three parameters of the setcookie( ) function allow you to restrict when it's sent, which gives you a little more control:
Once a cookie has been set, it becomes available to use on subsequent page loads through the $_COOKIE superglobal array variable. Using the previous call to setcookie( ), subsequent page loads can have their Name value read like this: print $_COOKIE["Name"]; |