Saving Form Data into a Cookie


 setcookie('formdata', serialize($formdata), time()+30*24*60*60); 


After the form has been submitted, the data must go somewhere, possibly in a database (see Chapter 8), in a file, or sent via email. When a website contains several similar forms (for example, forms that all require the user to provide his name and contact information), it is a good idea to save the data after the user fills it in. Because HTTP is a stateless protocol, you have to use cookies (see Chapter 6, "Using Files on the Server File System")sessions are useless because they expire when the user closes the browser.

Saving Data into a Cookie (getFormData.inc.php; excerpt)
 function setCookieData($arr) {   $formdata = getCookieData();   if ($formdata == null) {     $formdata = array();   }   foreach ($arr as $name => $value) {     $formdata[$name] = $value;   }   setcookie('formdata', serialize($formdata),     time()+30*24*60*60); } 

Because user agents only have to save 20 cookies per domain, it's a good idea to store the form information in one cookie, in the form of an array. However, only string values are allowed in cookies; this is why you have to serialize the array. The function shown in the listing at the beginning of this phrase writes the contents of the array provided as a parameter into the cookie.

The function getCookieData() returns the existing data from the cookie (if available) and unserializes it into an array. You will see the code in a later phrase.

The only thing left to do is to write the required form data into this array. You can specifically submit only certain values, or the complete array $_GET or $_POST, as shown in the following code.

Saving Form Data in a Cookie (save-cookie.php; excerpt)
 <?php   require_once 'stripFormSlashes.inc.php';   require_once 'getFormData.inc.php';   if (isset($_POST['Submit'])) {     setCookieData($_POST);   } ?> ... <?php   if (isset($_POST['Submit'])) {     echo '<h1>Thank you for filling out this form!</h1>';   } else { ?>   <form method="post" action="<?php echo      htmlspecialchars($_SERVER['PHP_SELF']); ?>">   ...   </form> <?php   } ?> 

Figure 4.2 shows the resulting cookie.

Figure 4.2. The serialized form data is saved in a cookie.


NOTE

Note that you have to save the form data prior to any HTML output. As cookies are sent as part of the HTTP header, they have to be declared before HTML starts (and, as a matter of consequence, the HTTP header ends). More information about the timing of cookies can be found in Chapter 6.





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net