Setting Up the Development Environment
Before a Flash movie can talk to a PHP script and write to a text file, the local machine has to host both a web server and the Flash authoring tool. The most common way to get everything running on Windows is to install PHPSuite, a lightweight bundle that ships Apache, PHP and phpMyAdmin in a single executable. Once PHPSuite is running, the document root lives atc:\phpdev\www\. If you prefer XAMPP, WAMP or MAMP, the instructions below still apply – just replace the paths accordingly.
Create a new folder inside the document root called exercise. That folder will hold the PHP script, the text file that receives the data, and the SWF that will be opened by your browser. In the same way, create an empty file called myTextFile.txt inside the exercise folder. Make sure the file has write permissions; on Windows this usually means the file can be edited by your user account. If the file ends up being read‑only, the PHP script will be unable to append data to it.
With the folder structure in place you can test the web server by navigating to http://localhost/exercise/ in a browser. If you see a blank page or a “file not found” error, double‑check that Apache is running and that the URL points to the correct location. Once the server is up and the file can be reached, the PHP side of the interaction can be written.
Open your favorite text editor – for example, SciTE – and create a file named careTaker.php in the exercise folder. The script must perform four tasks: open the text file, append a line containing the submitted data, report success or failure, and finally echo back the submitted data so that the Flash movie can display it. The full code is shown below; comments have been retained to explain each step.
<?php</p>
<p>// open the text file in read/write mode, create if missing</p>
<p>$myTextFileHandler = @fopen("myTextFile.txt", "a+");</p>
<p>if (!$myTextFileHandler) {</p>
<p>
// could not open the file – return an error to Flash</p>
<p>
print("&writeStatus=Unable to open text file");</p>
<p>
print("&receivedData=");</p>
<p>
exit;</p>
<p>}</p>
<p>// read existing content to determine how many lines have been written</p>
<p>$txtfileArray = file("myTextFile.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);</p>
<p>$count = count($txtfileArray) + 1; // line number for the new entry</p>
<p>// move pointer to the end of the file</p>
<p>@fseek($myTextFileHandler, 0, SEEK_END);</p>
<p>// write the new line; include a line break for readability</p>
<p>$writeInTxtFile = @fwrite($myTextFileHandler,</p>
<p>
"
received data from flash $count = " . $_POST['inputData']);</p>
<p>if ($writeInTxtFile !== false) {</p>
<p>
$writeStatus = "writing to textfile was a success";</p>
<p>} else {</p>
<p>
$writeStatus = "writing to textfile failed";</p>
<p>}</p>
<p>// close the file handle</p>
<p>@fclose($myTextFileHandler);</p>
<p>// return status and the original data back to Flash</p>
<p>print("&writeStatus=" . urlencode($writeStatus));</p>
<p>print("&receivedData=" . urlencode($_POST['inputData']));</p>
<p>?></p>
@ to silence PHP warnings that would otherwise flood the output. After a successful write the script prints two key/value pairs – writeStatus and receivedData – in the format that the LoadVars object expects. Those values will be available to the Flash side in the response.onLoad callback. If the file cannot be opened, the script stops early and only returns a status message; this allows Flash to detect and inform the user about the problem.
A couple of safety checks can be added before writing to the file. For instance, trim the incoming data and verify it is not empty. This prevents blank lines from cluttering the text file. In a production scenario you would also want to sanitize the input to avoid injection attacks, but for this learning exercise the focus is on the mechanics of sendAndLoad
At this point the PHP side is ready. The next step is to build the Flash interface that collects user input, sends it to the script, and displays the response. With the environment prepared, you can be sure that when the Flash movie is executed, the PHP engine will happily receive, store, and echo back the data. The local server ensures that cross‑domain restrictions do not block the request, because everything runs under the same domain – localhostBuilding the Flash‑PHP Interaction
Create a new Flash file in Adobe Flash Professional or Animate. Set the stage size to 300 × 300 pixels and give it a dark grey background to make the input fields stand out. In the library, draw a small square that will become the submit button; convert it to a symbol and name it submit, set its type to Movie Clip, and export it for ActionScript. Assign the instance name submit on the stage. Below the button place a dynamic text field – instance name statustxtb – sized 270 × 17 pixels; this will display whether the write succeeded. Next to it add another dynamic text field, responsetxtb, the same width as the input field; this will show the raw string that arrived back from PHP. Finally, create an input text field named inputData and label it with a static text field that reads “input some text to store:”.
With the visual layout complete, open the timeline on the first frame and add a new layer called “code”. Inside that layer paste the ActionScript code below. The code is deliberately simple but covers the entire workflow: creating a LoadVars object for the outgoing request, another for the incoming response, and wiring an onLoad handler to process the results. All URLs point to http://localhost/exercise/careTaker.php – remember to adjust the path if you are using a different server or folder name.
var submittedData:LoadVars = new LoadVars();</p>
<p>var response:LoadVars = new LoadVars();</p>
<p>// Callback that runs after the PHP script has finished</p>
<p>response.onLoad = function(success:Boolean):Void {</p>
<p>
if (success) {</p>
<p>
// show the data that PHP echoed back</p>
<p>
responsetxtb.text = response.receivedData;</p>
<p>
// show status of the write operation</p>
<p>
statustxtb.text = response.writeStatus;</p>
<p>
} else {</p>
<p>
trace("Flash failed to load the PHP response");</p>
<p>
}</p>
<p>};</p>
<p>// The function that starts the whole process</p>
<p>function submitDataToTextfile():Void {</p>
<p>
submittedData.inputData = inputData.text; // collect user input</p>
<p>
// send data to PHP and load the response into the 'response' object</p>
<p>
submittedData.sendAndLoad(</p>
<p>
"http://localhost/exercise/careTaker.php",</p>
<p>
response,</p>
<p>
"post"</p>
<p>
);</p>
<p>}</p>
<p>// Hook the function to the button release event</p>
<p>submit.onRelease = submitDataToTextfile;</p>
When the button is clicked, the submitDataToTextfile function pulls the text from the input field and places it into a LoadVars object. The sendAndLoad method performs an HTTP POST to the PHP script and, upon completion, populates the response object with the data that PHP echoed. The onLoad callback receives a Boolean indicating whether the load succeeded; if it did, the dynamic text fields are updated with the values that the script returned.
You can test the entire flow by publishing the SWF to the exercise folder, then opening http://localhost/exercise/ in a browser and loading the SWF. Enter some text into the input box and hit the button. The text should appear in the response box, and the status box should read “writing to textfile was a success”. Open myTextFile.txt in a text editor to confirm that the line was appended. Re‑submit different values and watch the line number in the file increase – the PHP script counts how many entries exist before writing the new one, ensuring each entry is numbered.
If anything goes wrong, check the following: the URL in sendAndLoad matches the server location, Apache is running, the PHP script has execute permissions, and the text file is writable. The trace output in Flash (visible in the debug console) will report a failed load, and the status text will show “writing to textfile failed” if PHP couldn’t write to the file.
The example demonstrates the core concept of using LoadVars.sendAndLoad to bridge Flash and PHP. With a little extra logic you could extend this to validate input, strip whitespace, or even read from the text file and send back a list of all entries. The same pattern works for any server‑side language that can read POST data and echo back a key/value string. By mastering this flow you gain a solid foundation for building Flash applications that depend on dynamic data stored on a web server.





No comments yet. Be the first to comment!