How to make an SWF read result from a PHP? - php

I need to make a SWF that should show some data from the DB.
The DB will be read using PHP.
I was thinking that the SWF would get the data by accessing "data.php" and data.php will read from the DB. The SWF would read the XML/JSON/RAW DATA from that file and update it's variables.
How can I do this ? any reference maybe ?
Thanks!

The best way to intercommunicate Flash and PHP is XML (don't forget to use UTF-8!).
in "data.php":
$xml = new DOMDocument('1.0', 'UTF-8');
$doc = $xml->appendChild($xml->createElement('my-root-element'));
...
header('Content-Type: text/xml; charset=utf-8');
echo $xml->saveXML();
In "test.as"
var myLoader:URLLoader = new URLLoader();
var req:URLRequest = new URLRequest('http://.../data.php');
myLoader.addEventListener(Event.COMPLETE, onMyXMLLoad);
myLoader.load(req);
function onMyXMLLoad(e:Event)
{
trace(e.target.data);
var xml:XML = new XML(e.target.data);
...
}

Related

Php actionscript bitMapData post image

I would like to be able to display an image on the file script.php with the help of data transmitted by this code (Actionscript)
I get data by the POST method but I do not know what to do with it.
header('Content-Type: image/jpeg');
I don't know what to do with $_POST
public function onTakePhoto(param1:Event) : void
{
var _loc1_:Bitmap = new Bitmap(new BitmapData(680,440));
var _loc2_:Matrix = new Matrix();
_loc2_.translate(-290,-150);
_loc2_.scale(2,2);
_loc1_.bitmapData.draw(DisplayObject(something),_loc2_);
var _loc3_:ByteArray = new ByteArray();
_loc1_.bitmapData.encode(_loc1_.bitmapData.rect,new JPEGEncoderOptions(),_loc3_);
var _loc4_:URLRequest = new URLRequest("script.php");
_loc4_.method = URLRequestMethod.POST;
_loc4_.data = _loc3_;
navigateToURL(_loc4_,"_blank");
_loc1_.bitmapData.dispose();
}
You can fetch the $_POST data like this:
$image_data = file_get_contents("php://input");
//proceed by perhaps saving the image to the server:
file_put_contents('path/to/save/image.jpg',$image_data);

accessing parsed JSON (generated via php) in native Actionscript3 (Flash)

Okay, here goes. I'm sure I'm only missing a small thing somewhere.
I'm trying to do a little Highscore System for my game and thus I have a php script on a webspace for the programm to access (I have literally 0 experience with php):
<?php
$json = json_encode($_REQUEST);
$fileSave = fopen("processdata.txt", "a+") or die ("Can't create processdata.txt");
fwrite($fileSave, $json);
fclose($fileSave);
print($json);
?>
processdata.php
then, in actionscript, I juse this code to access the file and parse it:
//set variables to send to the php script
var variables:URLVariables = new URLVariables();
variables["name"] = "Player1";
variables["points"] = 123;
//set request to load php script
var request:URLRequest = new URLRequest("processdata.php");
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, httpRequestComplete);
loader.load(request);
//php script finished
function httpRequestComplete(_e:Event){
//load processdata.txt
var uLoader:URLLoader = new URLLoader();
var uReq:URLRequest = new URLRequest("processdata.txt");
uLoader.addEventListener(Event.COMPLETE, getProcessdata);
uLoader.load(uReq);
}
//loading of processdata.txt finished
function getProcessdata(_e:Event){
var rawData : String = _e.target.data;
//convert the input string in readable JSON
rawData = rawData.split('"').join("\\\"");
rawData = "\"" + rawData + "\"";
//convert into JSON
var proData:Object = JSON.parse(rawData);
}
here is what processdata.txt looks like (for example)
{"name":"Player1","points":"123"}{"name":"Player2","points":"234"}
this is then converted in my AC into this (to make it readable for the JSON.parse):
"{\"name\":\"Player1\",\"points\":\"123\"}{\"name\":\"Player2\",\"points\":\"234\"}"
Now, how to I access the parsed JSON String? I tried all of those and nothing works:
proData.name;
proData[name];
proData["name"];
proData[0];
proData[name[0]];
for (var obj : String in proData){
obj;
}
Any help is appreciated. Doesn't matter where you find a possibility to make this work (PHP, AC3, JSON, etc)
Also, if you have a simple possibility for me to change my php in a way that it creates xml instead of php, I can do the rest from there, I get my Code to work with a XML File.
Thanks in advance.
You should know that your JSON content is not valid and that's why you can get nothing from it in the ActionScript side.
As you are saving players scores, you can store your data as an array :
[
{
"name": "Player1",
"points": "123"
}, {
"name": "Player2",
"points": "234"
}
]
but to get that, you've to edit your PHP code like this, for example :
<?php
$json_file = 'scores.json';
$new_score = $_REQUEST;
if(file_exists($json_file))
{
// get stored scores
$scores = json_decode(file_get_contents($json_file));
} else {
// create an empty array to store scores
$scores = array();
}
// add the new score to scores array
array_push($scores, $new_score);
// persist scores array as json content
file_put_contents($json_file, json_encode($scores));
?>
then in the ActionScript side, you can do :
function getProcessdata(e:Event) : void
{
var rawData:String = e.target.data;
var data:Array = JSON.parse(rawData) as Array;
for(var i:int = 0; i < data.length; i++){
trace(data[i].name); // gives for example : "Player1"
}
}
Hope that can help.

echo not returning variable value on php actionscript connection

I'm trying to pass some variables from php to flash, im using this actionscript code:
public function gameOver(score:Number)
{
totalScore.text = score.toString();
var scriptVars:URLVariables = new URLVariables();
scriptVars.score = score;
var scriptLoader:URLLoader = new URLLoader();
var scriptRequest:URLRequest = new URLRequest("checkScores.php");
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
}
function handleLoadSuccessful(e:Event):void
{
trace("Scores Loaded");
var vars:URLVariables = new URLVariables(e.target.data);
nickname1.text = vars.nickname;
score1.text = vars.score;
}
function handleLoadError($evt:IOErrorEvent):void
{
trace("Load failed.");
nickname1.text ="error";
}
And this php code:
<?php
... some code for the mysql connection and select sentence ...
$topScores = mysqli_query($con, $topScores);
$topScores = mysqli_fetch_array($topScores);
echo "&nickname=$topScores[nickname]&score=$topScores[score]";
?>
both runs without errors, the problem is that what i get on flash aren't the variables values but the name of the variables, in other words what i get on vars.nickname is
$topScores[nickname]
and for vars.score
$topScores[score]
If i run the php alone i get this:
&nickname=jonny&score=100
which are the actual variable values i'm trying to get, any help would be greatly appreciated.
I think you may just be loading up the php file as a text file from flash. Can you change the following line:
new URLRequest("checkScores.php");
to something like:
new URLRequest("http://localhost/checkScores.php");
or whatever you see in the browser address bar when you "run" it as you said in your question.

Actionscript 3 - Reading String from PHP echo

i have a php script that print with echo this:
'&string="tom,dick,harry"'
and i need to put the "tom,dick,harry" in an actionscript string, that i have to split in an array. I'm having problems reading the php output, i'm using the URLLoader and TheURLVariables Classes in this way
var myRequest:URLRequest = new URLRequest("ip/directory/script.php");
var myLoader:URLLoader = new URLLoader();
function onLoaded(event:Event):void {
var variables:URLVariables = new URLVariables( event.target.data );
modelli = variables.string.split(",");
caricaColori(modelli[0]);
}
myLoader.addEventListener(Event.COMPLETE, onLoaded);
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myLoader.load(myRequest);
What am i doing wrong?
Thought that you got problem with URLVariables, I still not totally understand this yet
function onLoaded(event:Event):void {
var variables:URLVariables = new URLVariables( event.target.data );
modelli = variables.string.split(",");
caricaColori(modelli[0]);
}
why do you need to store it into a URLVariables instance? Why don't parse it directly. If you are afraid of the "&string=", you don't need to echo it on PHP side, or can slice it out on Actionscript side.
modelli = event.target.data.split(",");
Perhaps using a variable name that isn't reserved might help. string seems like a bad choice.
// in php change
echo '&string="tom,dick,harry"'
// to
echo "tom,dick,harry"
// in actionscript change
function onLoaded(event:Event):void {
var str:String = event.target.data;
modelli = str.split(",");
caricaColori(modelli[0]);
}
If you want to add more variables and whatever, I would suggest turning the php response into an xml file. URLVariables should be used to SEND data to the server not for parsing a server response.
LOOK HERE
function onLoaded(event:Event):void {
var variables:URLVariables = new URLVariables( event.target.data );
modelli = variables.string.split(",");
caricaColori(modelli[0]);
}
Your problem is that you're loading the variables into a URLVariables container, and then trying to call a string function on it. I would do it this way instead:
function onLoaded(event:Event):void {
//load data as a string
var variables:String = event.target.data;
//make a new array
var modelli:Array = new Array();
modelli = variables.split(",");
//possibly pop the array
modelli.pop(); //pop off the last empty element of array
caricaColori(modelli[0]);
}
There's also a good chance that when you load this PHP data, you'll need to pop() the last element off of the array because it will be an empty string.

Flash calling a PHP function

is it possible to call a PHP function from flash and have it execute right away?
If so how could I go about doing that, because I am trying to call a PHP function that will update a users facebook status, but thus far I have been unsuccessful, so I am kind of at the end f my rope.
Any help would be appreciated, thanx!
My idea would be something similar to the following:
function updateFBStatus(newStatus)
{
// create two new instances of LoadVars, one to send and one to receive data
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
// define what should happen when the response is received,
// using 'this' to refer to dataIn and get data from it
dataIn.onLoad = onReturn;
dataOut["newStatus"] = newStatus;
dataOut.sendAndLoad(serverURL+"setFBStatus.php", dataIn, "POST");
}
You then define the setFBStatus.php file on your server to read $_POST['newStatus'] and do whatever you would normally do in php to set the facebook status. That php file can optionally echo some return values in url request format (i.e, paramName1=param1&paramName2=param2&) for your onReturn function to read, if you need to.
Have a look at AMF PHP!
Save the PHP function in facebookFunction.php and call it using a URLLoader.
var urlLoader:URLLoader = new URLLoader();
var data:URLVariables = new URLVariables();
//you can use dot syntax and/or [] syntax to add data.
data.user = "kiele";
data["someThingElse"] = "something else";
var req:URLRequest = new URLRequest("facebookFunction.php");
req.data = data;
urlLoader.load(req);
At the php side, you can read the values from the global get variable.
$user = $_GET["user"]
The way I would do it is in the flash actionscript is call a javascript function using getURL("javascript:someFunction(var-1, var-2, var-n)") http://www.adobe.com/livedocs/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001180.html
That javascript function can then do an ajax request to a php script.
EDIT:
you could just post data directly without using AJAX:
var firstName:String = "Gus";
var lastName:String = "Richardson";
var age:Number = 92;
getURL("http://www.adobe.com", "_blank", "POST");
Why you are not using a Flash API for Facebook: http://code.google.com/p/facebook-actionscript-api/ ?

Categories