PHP

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 tutorial 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 tutorial 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
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 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 coding.

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
<?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 shows the resulting cookie.

The serialized form data is saved in a cookie.

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 tutorial 6.

by BrainBellupdated
Advertisement: