Categories
PHP

Saving Form Data into a File

Learn how to serialize (and unserialize) the form data in PHP for storing it in a file.

<?php
 $data = serialize( $_POST );
 file_put_contents('formdata.txt', $data);

After validating a form, what do you do with the form data? A very rear approach that does not require too much setup on the server is to write the data into a file on the server.

Example: Writing Form Data into a File:

<?php
 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  echo '<h1>Thank you for filling out this form!</h1>';
  $data = file_get_contents('formdata.txt');
  if ($data != '') {
   $data = unserialize($data);
  }
  $data[] = $_POST;
  file_put_contents('formdata.txt', serialize($data));
 }

In the above code, all data is stored in a file on the server. When the form is submitted, the file is read in and unserialized into an array. Then, the form data is appended to the array. Finally, the array is serialized again and written back to the file.

Note: the file could be simultaneously read by two processes, to avoid this, implement file locking.

serialize()

The serialize() function returns a string containing a byte-stream representation of any value that can be stored in PHP. This function handles all data types, except the resource type (for example, DB connections and file handlers).

Example: Serializing query string

<?php
 $qs = serialize ( $_GET );
 echo $qs;

The preceding code prints the following output on my localhost:

URL:
http://localhost/example.php?domain=brainbell.com&category=php

Output:
a:2:{s:6:"domain";s:13:"brainbell.com";s:8:"category";s:3:"php";}

Example: Serializing an array

<?php
 $arr = array('PHP', 'ASP', 'JSP');
 $ser = serialize( $arr );
 echo $ser;
 //a:3:{i:0;s:3:"PHP";i:1;s:3:"ASP";i:2;s:3:"JSP";}

unserialize

The unserialize() function is used to recreate the original variable values (bool, int, float, string, array, or object) from a serialized string.

Example: Unserializing a string data

<?php
 $arr = unserialize('a:3:{i:0;s:3:"PHP";i:1;s:3:"ASP";i:2;s:3:"JSP";}');
 foreach ($arr as $v)
  echo "$v ";
 // PHP ASP JSP

Processing Forms in PHP: