write to text file

Flash alone can’t write to a text file.
Although this is a simple and very useful task, flash needs the help of a server side scripting language like PHP to do it.

PHP is very powerful and can create, delete, read text files and write to them.

Usually flash loads variable name/value pairs or xml. As this isn’t what we’ve got now (we have plain text), I’m going to use a PHP script to load the content of the text file. Notice that this could be achieved just by using the onData() method from the LoadVars Class in flash.

This article assumes that you have a basic understanding of ActionScript and PHP and that you have PHP running. An easy way to install PHP is installing wampserver (it also installs Apache, MySQL, …)

For this simple example, in flash, all you need is an input TextField, a submit button and some ActionScript to send and load variables to and from the PHP script(s).
Initially I use two PHP files: one to read the text file and another one to write to it. In this example test.txt is the default name for the text file.

But the same result can be achieved with one file only.
In readAndWrite.php, the script checks for the value of the variable $action that comes from flash in order to decide what to do (read or write).
In this example you have the ability to specify a name for the text file – both to read from and write to. This allows you to create different text files.

The whole idea can be explained in three steps:

  • passing variables from flash to the php scripts and vice versa
    the LoadVars Class is used
  • a php script is used to open a file and write to it
    fopen and fwrite are used
  • a php script is used to open a file and read it
    fopen and fread are used

You can download the files here.
I commented all the code, both in the php files and in flash, so you should be able to understand everything by reading them.