The University of Texas at Austin- What Starts Here Changes the World
Services Navigation


Example 5 - Writing Form Data to a File

The previous example illustrated how to use PHP to read form data. In many cases you will also want to store the information submitted in a file or database. For example, if you are conducting an online survey you would want to write the survey results to a file so you can analyze them later. This example reads the input from the Example 4 form and writes it to a tab-delimited text file on the server.

In order to properly store the files on this server and increase the security of your data, your PHP scripts will need to run as CGIs. be located in a specific location. The files that you save can be located anywhere within your directory space, however the PHP script should be located in your publishing space in your home directory. For more details on how to set up your home directory, please see the documentation on setting up CGI-WRAP.

If you are new to Unix, we also recommend that you look at a quick overview of common UNIX Commands.

<HTML>
<HEAD>
<TITLE> Example 5 </TITLE>
</HEAD>
<BODY>

<?  

// The next line opens a file handle to a file called output.txt
// the file handle is like an alias to the file
// the a in the fopen function means append so entries
// will be appended to the output.txt file

$out = fopen("output.txt", "a");
 
// if the file could not be opened for whatever reason, print 
// an error message and exit the program

if (!$out) {
    print("Could not append to file");
    exit;
}

// fputs writes output to a file.  the syntax is where to write
// followed by what to write

// $name is the contents of the name field in the sample form
// \t represents a tab character and \n represents a new line


fputs($out,"$_POST[name]\t");
fputs($out,"$_POST[yearborn]\t");
fputs($out,"$_POST[favcolor]\t");
fputs($out,"$_SERVER[REMOTE_ADDR]\n");
print("Thanks you for completing our survey.  You have been assimilated.");

fclose($out);

?>


</BODY>
</HTML>

The key elements of the above example are the fopen function to open the output.txt file for appending and the fputs statements to put things into those files.

Note for UT Austin Web Central Users: Because Web Central runs PHP in safe mode, the file that you write to must already exist (it can be empty) and it must be either owned by you or group writable by the Web server. WE encourage you to execute PHP scripts that need to write data in your home directory on UTS. If you have questions about this, we suggest making an appointment with a Teamweb consultant.

Test Example 5

View Source Code

PHP Manual Pages

 
   

  Updated 2011 June 17
  Comments to www@www.utexas.edu