Tuesday, December 30, 2008

Flash & PHP Communication - Reading Writing Text Files




Flash & PHP - Reading Writting Text Files

Step 1
Create a flash AS3.0 from your Flash CS3. Add the document class as "Main" or of any name keeping in consideration the "as" file name. I used "Main" as my class name. Here is the code for the "Main" class.

Main.as
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.net.sendToURL;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.navigateToURL;
import flash.events.Event;
public class Main extends MovieClip{
public var urlrequest:URLRequest = new URLRequest("http://localhost/flash_write/saveData.php");
public var urlLoader:URLLoader = new URLLoader();
public function Main(){
init();
}
private function init(){
_save.addEventListener(MouseEvent.MOUSE_DOWN, saveallData);
}
private function saveallData(evt:MouseEvent):void
{
urlrequest.method = URLRequestMethod.POST;
var _vars:URLVariables = new URLVariables();
_vars.sendname = _nameBox.text;
urlrequest.data = _vars
sendToURL(urlrequest);
var loader:URLLoader = new URLLoader (urlrequest);
loader.addEventListener(Event.COMPLETE, onComplete);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlrequest);

}
function onComplete (event:Event):void{
var variables:URLVariables = new URLVariables(event.target.data);
_requestBox.text = variables.finalData;
}
}

}

Step2
We need to create some interface for writting in a reading the text file. I will show a sample as i made it. You can see the blue interface at top of the blog.

Step3
Now we need to add the PHP script. It can be any simple script for reading or writting to a text File. I am adding my script below for reference.

saveData.php
$content = $_POST["sendname"];
$fp = fopen("newfile.txt", "a") or die("Couldn't create new file");
$numBytes = fwrite($fp, $content."\r\n");
fclose($fp);

$fp = fopen("newfile.txt", 'r');
$theData = fread($fp, filesize("newfile.txt"));
fclose($fp);

$numVariables = 0;
function writeVariable( $name, $value )
{
if( $numVariables > 0 )
{
echo "&";
}

echo $name . "=" . urlencode($value);

$numVariables ++;
}

writeVariable( "finalData", $theData );

?>

You will need any PHP server to run this script. I used WAMP server which can be downloaded from below link.

Link to File

A Blank Text File "newfile.txt" should be placed on the server as PHP Script is appending to it.


Thanks-


Using FormBuilder, Validators & FormGroup in Angular 2 to post data to Node server (node.js)

This blog explains usage of  FormBuilder , Validators , FormGroup classes in Angular 2 projects. In this post we will create HTML form a...