Saving Form Data into a File

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

 $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:

  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.


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

 $qs = serialize ( $_GET );
 echo $qs;

The preceding code prints the following output on my localhost:



Example: Serializing an array

 $arr = array('PHP', 'ASP', 'JSP');
 $ser = serialize( $arr );
 echo $ser;


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

 $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 ";

Processing Forms in PHP: