AS3 -> PHP Foreign Characters giving incorrect information - php

I'm far from an expert in PHP and I'm struggling to resolve an issue that I'm having here.
What I'm doing is pulling core information from this URL:
http://us.battle.net/wow/en/arena/kelthuzad/3v3/W%C3%BCstenfuchs%20zu%20gro%C3%9F/
In AS3 this provides me with the following, from the team name:
http://us.battle.net/wow/en/arena/kelthuzad/3v3/W%C3%BCstenfuchs%20zu%20gro%C3%9F/
Now, this is fine. If I decodeURI it, it gives me:
http://us.battle.net/wow/en/arena/kelthuzad/3v3/Wüstenfuchs zu groß/
My issue comes when I'm sending the information from AS3 to PHP. I'm doing it with encoding intact, however no matter what I try PHP is reading the code incorrectly. This is the output:
var9=http://us.battle.net/wow/en/arena/kelthuzad/3v3/Wüstenfuchs zu groÃ/
Even when I try to decode this, it gives the exact same output. If I send it from AS3 to PHP already decoded, it again gives the same result as above.
My code for AS3 is:
var phpVars:URLVariables = new URLVariables();
phpVars.team = _team;
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = phpVars;
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, returnResult);
urlLoader.load(urlRequest);
My code for PHP is:
header("Content-type: text/html; charset=utf-8");
function updateData(){
$team2 = mysql_real_escape_string($_POST['team']);
echo("var9=".$team2);
$sql = "INSERT INTO title_test SET field1='$team2'";
mysql_query($sql);
}
This puts into the database:
http://us.battle.net/wow/en/arena/kelthuzad/3v3/Wüstenfuchs zu groß/
It's also worth noting that I'm trying to do a query with the $team2 data within PHP that is also failing, as it is not encoding correctly.
What step am I missing here?
Edit: utf-8 is enabled on the DB.

Per http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html , add
mysql_query('SET NAMES UTF8');
just before
mysql_query($sql);
If that doesn't work, then make sure you are sending UTF8 to the server:
echo 'team2=', bin2hex($team2);
You should see
team2=57c3bc7374656e6675636873207a752067726fc39f
if you are sending UTF8.

Okay, after much heartache and many headaches, I have now got this to work... However the method that makes it work seems very strange and not best practise.
AS3 is now:
var phpVars:URLVariables = new URLVariables();
phpVars.team = decodeURI(_team);
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = phpVars;
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, returnResult);
urlLoader.load(urlRequest);
PHP is now:
$team2 = ($_POST['team']);
echo("var9=".$team2);
$sql = "INSERT INTO title_test SET field1='$team2'";
mysql_query($sql);
Connect.php is now
mysql_connect($db_host, $db_username, $db_password, $db_name);
mysql_query('SET NAMES utf8');
mysql_select_db($db_name) or die (mysql_error());
This now correctly returns information into the database and allows the URL queries to work. The echo'd information back into Flash still shows incorrectly, though.
I'll leave this open, as I'm certain that this method is incorrect. I'm almost certain that you should leave it encoded going out of AS3 and unencode it in PHP.

Related

how can I migrate to AS3 with code like this "l = new LoadVars ();"

i am a beginner. I'm starting to learn Adobe Flash. I followed the code on Google on AS2:
l = new LoadVars();
l.onLoad = function(ok) {
ttl0=l.ttlslv0; atc0=l.atcslv0;
ttl1=l.ttlslv1; atc1=l.atcslv1;
};
l.sendAndLoad("http:localhost/getdata.php", l, "POST");
with php like this:
<?php
include_once("koneksi.php");
$qr = mysqli_query($con,"SELECT title, article from $tabel");
$nr = 0;
while($kolom=mysqli_fetch_row($qr) )
{
$ttl=$kolom[0];
$atc=$kolom[1];
echo "&ttlslv$nr=$ttl&atcslv$nr=$atc";
$nr++;
}
echo "&nr=$nr&";
?>
with the results that I can specify "what row" and "what column" will I take.
can this be changed to AS3 with the same results?
I have difficulty studying AS3
anyone want to give me a solution? thanx...
In AS3 you use the URLLoader class to load text/binary data. To work with URL-encoded strings you need the URLVariables class.
Something like that (not tested, no error handling either, just a common guideline):
// URLRequest instance holds various information
// about what, where and how you send.
var aRequest:URLRequest = new URLRequest;
// URL address.
aRequest.url = "http://localhost/getdata.php";
// Request method (POST or GET mostly).
aRequest.method = URLRequestMethod.POST;
// URLLoader instance performs the requested operations:
// uploads the request and relevant data, reads the answer,
// and dispatches all the events about any status changes.
var aLoader:URLLoader = new URLLoader;
// Tell the URLLoader that the answer is
// an URL-encoded text of key=value pairs.
aLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
// This event handler function will be triggered
// upon successfully completed operation.
aLoader.addEventListener(Event.COMPLETE, onData);
// Start loading.
aLoader.load(aRequest);
// The COMPLETE event handler function.
function onData(e:Event):void
{
// Unsubscribe from the event. For the most part it is
// a GOOD idea NOT to re-use any network-related
// class instances once they've done their job.
// Just unsubscribe from all their events,
// dismantle their data structures, purge
// any references to them and let the
// Garbage Collector do his job.
aLoader.removeEventListener(Event.COMPLETE, onData);
// Retrieve the object that contains key=value pairs.
var anAnswer:URLVariables = aLoader.data as URLVariables;
// The data you wanted to get.
trace(anAnswer.ttlslv0);
trace(anAnswer.atcslv0);
trace(anAnswer.ttlslv1);
trace(anAnswer.atcslv1);
}
UPD: It seems that you are dealing with escaped text there. I composed a simple script that explains how it works:
import flash.net.URLVariables;
var V:URLVariables = new URLVariables;
var S:String = "a=1&b=2";
V.decode(S);
trace(V.a); // 1
trace(V.b); // 2
S = escape(S);
trace(S); // a%3D1%26b%3D2
trace(unescape(S)); // a=1&b=2
V.decode(S); // Error #2101
So, there are two options you can work on:
Figure out why server passes the escaped string and prevent it.
Load the server's answer as a plain text (URLLoaderDataFormat.TEXT instead of VARIABLES) so the URLLoader.data will be just a simple String, then unescape(...) it if necessary and feed to the URLVariables.decode(...).

Parsing PHP in ActionScript returns "undefined"

I know this question has been asked before, but I've had little success even after visiting similar questions. I'm currently developing a Flash project which involves being able to create an account and log in. However, I keep getting "undefined" from my attempts to parse PHP output.
Here is my ActionScript 3.0 code for the function that contains the code.
function gosubmit(event:MouseEvent) {
if (username.text != "" && password.text != "") {
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest();
phpFileRequest.url = "php/controlpanel.php";
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, execResult);
phpVars.username = username.text;
phpVars.password = password.text;
phpLoader.load(phpFileRequest);
phpLoader.addEventListener(Event.COMPLETE, execResult);
function execResult(event:Event) {
trace(event.target.data.execResult);
}
}
Here is the PHP code in php/controlpanel.php.
<?php
mysql_connect("localhost", "root", "password");
// change localhost to something else later
// change password to something else later
mysql_select_db("game");
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$salt_mysql = mysql_query("SELECT salt FROM players WHERE username='".$username."'");
$salt = salt_row["salt"];
$unhashed_password = $password.$salt;
$password = hash("SHA256", $unhashed_password);
$exec_mysql = mysql_query("SELECT * FROM players WHERE username='".$username."' AND password='".$password."'");
if (mysql_num_rows($exec_mysql)) == 1 {
echo "execResult=login_accepted";
}
if (mysql_num_rows($exec_mysql)) == 0 {
echo "execResult=login_rejected";
}
else {
echo "execResult=error";
}
?>
I have compared my code with multiple sources, even copied whole projects from sources trying to figure out what I have done wrong, but with little success. However, there is something weird I found out. Out of pure experimentation, I put the following into controlpanel.php:
=&execResult=test
And, instead of getting "undefined", I got "test". The weird part is that I only used that one line of code; no <?php tags or anything. Moreover, if I put more code beyond that, regardless of what kind of code I entered, it would always show up literally in the Flash output. So I can now hardcode a value and return it into Flash, but that's not what I need. I need to be able to determine a value based on conditionals and have it automatically returned into Flash.
Can anyone help me out? I am truly stumped.
Thanks :)
Seems that you are executing flash from the editor/debugger, (if you are checking the results with trace function).
Then using a relative url for request "php/controlpanel.php" is like opening the file localy without the execution from server of php directives.
Maybe thats why you get literaly all php code, or the correct value when you only put "=&execResult=test" as the content of the php file.
Try using absolute url with the http:// in order to perform an http request where server and php execution are involved.

Passing arrays from Flash to PHP

I am having a problem passing an array variable from Flash (AS2) to PHP. In action script I have several arrays defined like this
output["px1"]
output["px2"]
output["px3"]
and then I use the following code to pass the variables into a php file
output.sendAndLoad("orders/print2cart.php",output,"POST");
I want to know how to get the data from the array in PHP. I have tried using $_POST['px1'], $_POST['output']['px1'], $_POST['output'] but I cannot seem to get any data. Any ideas as to what I can change to get the desired result?
Thanks!
EDIT: Just noticed that I one of the other variables in output (output.username) is also not being sent to PHP, despite it showing up in flash. Using the following code to alert to flash and it does show all the variables correctly.
getURL("javascript:alert('Print Stamp: " + output.PrintStamp + " User: " + output.username "')");
EDIT: Seems like once I send a pretty long array (or a string for that matter) none of the other fields associated with the LoadVars variable are sent either. I googled it up for limits and it says text limits are ~ 63000. Still not sure if that is the problem
Try it as a String.
Use Array.join(); in flash and send the value returned by that, then use explode() in PHP convert it back to an array.
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
dataOut.info = your_array.join("#");
vars.sendAndLoad("url", dataIn, "post");
dataIn.onLoad = function(go:Boolean):Void
{
if(go)
{
trace('success');
}
else trace('connection failed');
}
The PHP:
<?php
$str = $_POST["info"];
$myarray = explode($str);
?>
Since there were no other alternatives and I went through a lot of stuff before finally concluding that Arrays of large sizes cannot be passed through from AS2 to PHP very easily. My array was actually an image converted to pixels, so what I did was that I split the array into 2 pieces and posted to the PHP file twice instead of only once. Another alternative would be to split and post the array to a text file first and then read that text file directly from PHP.
You can do the same as you would do with HTML, by naming your parameters "array[0]", "array[1]", etc... :
var urlVariable:URLVariables = new URLVariables();
urlVariable["phpArray[0]"] = "arrayEntry0";
urlVariable["phpArray[1]"] = "arrayEntry1";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://yourserver.com/phpScript.php");
request.method = URLRequestMethod.POST;
request.data = urlVariable;
loader.load(request);
then serverside you can verify the result received by php script :
print_r($_POST);
it should output :
Array
(
[phpArray] => Array
(
[0] => arrayEntry0
[1] => arrayEntry1
)
)
and for multiple dimension array you can use :
urlVariable["phpArray[0][0]"]

How do I POST XML data to a URL via JavaScript in an Adobe AIR app?

I'm writing an application that downloads an XML string from a URL and POSTs that to another URL (that's set up to handle an incoming "XML" field). I've got the first part right - it downloads the XML and I can alert() it and all that, but I'm unable to figure out how to POST that data to a server.
function pull() {
var myLoader = new air.URLLoader();
var myRequest = new air.URLRequest('http://something/something.xml');
myLoader.addEventListener(air.Event.COMPLETE, pulled);
myLoader.load(myRequest);
}
function pulled(evt) {
if (evt.target.bytesTotal>0) {
// alerting shows the full string just fine
alert(evt.target.data);
var myLoader = new air.URLLoader();
var myRequest = new air.URLRequest('http://someplace/push.php');
myRequest.method = air.URLRequestMethod.POST;
// myVars = new air.URLVariables("xml="+evt.target.data); //
// alert(evt.target.data.toUpperCase());
myRequest.data = "xml="+evt.target.data; // myVars;
myLoader.dataFormat = air.URLLoaderDataFormat.TEXT;
myLoader.addEventListener(air.Event.COMPLETE, pushed);
myLoader.load(myRequest);
}
}
I made the 2nd server PHP echo the contents of the xml variable, but I'm just unable to get the exact contents of the XML string. There is something I'm doing wring with the myRequest.data and/or dataFormat bit.
Can someone just figure this out? I know it's probably a simple thing, but I'm at my wit's end right now.
This is my first AIR app.
Another related question (or sub-question) is that...
alert(evt.target.data); // shows an alert box with the XML
alert(typeof evt.target.data); // shows String
alert(evt.target.data.toUpperCase()); // shows the xml converted to upper case
alert(encodeURI(evt.target.data)); // shows up blank.
alert(escape(evt.target.data)); // shows up blank.
Why??
The error seems to be the way you are assigning the parameters to 'data' ... Use URLVariables.
var params:URLVariables = new URLVariables();
params.[name of parameter] = [value];
--- so like params.xml = (YOUR XML) ... from your example:
// uses the dynamic object to add the 'xml' property to 'params' at runtime.
params.xml = evt.target.data
Then Change you request.data to request.data = params;
-- The URLVariables guy is dynamic - so you can add properties as I describe above.
For a basic example - much more complete that what I have here: http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_2.html

Sending ByteArray to Zend_Amf

I'm having problems sending a ByteArray over to my Zend_Amf_server. I get a NetConnection.Bad.Call back from the server. If I send a variable with another datatype then ByteArray it works fine.
I used the same script before with AMFPHP witouth any problems. But for this project I really need this to work in Zend_Amf.
AS3:
var path:String = "/images/picture.jpg";
var ba:ByteArray = jpgencoder.encode(bitmap.bitmapData);
var nc:NetConnection = new NetConnection();
nc.connect(zend_amf_server);
nc.call("Service.saveJPG", new Responder(responseHandler, errorHandler), path, ba);
PHP:
class Service{
public function saveJPG($path, $byteArray){
return "worked";
}
}
I was getting the same error from Zend AMF tonight doing basically the same thing with code that previously worked in AMF. Here's what I have that's working. The only bit I spot different from your code is I'm only passing the ByteArray to Zend, and I'm explicitly setting the ObjectEncoding.
I kept getting empty jpgs on the server because I'd read elsewhere that I needed to do ->data to get to the ByteArray data.
AS3:
_service = new NetConnection();
_service.objectEncoding = ObjectEncoding.AMF3;
_responder = new Responder(this._onSuccess, this._onError);
_service.connect(zend_amf_server);
var myEncoder:JPGEncoder = new JPGEncoder( qualityValue );
var myCapStream:ByteArray = myEncoder.encode ( myBitmapSource ); // myBitmapSource is BitmapData drawn from a Sprite
this._service.call("Remote.savePhotoToServer", this._responder, myCapStream);
PHP:
function savePhotoToServer ( $pInfos )
{
$bytearray = $pInfos;
$idimage = $this->nameImage(".jpg"); // calls a private func for a new name
return ( $success = file_put_contents("./_photos/".$idimage, $bytearray) ) ? $idimage : $success;
}
Thanks David for your reply, the problem seemed to be that I sent a ByteArray to Zend_Amf together with a String.
If I send the ByteArray only it works fine and the Image is saved.
The only problem now is that the path to save the image on should be variable and I can't send it over to my Amf_Server together with the ByteArray at the same time.
Ok, I found the problem. I was using the Zend Framework in the latest 'tag' repository v. 1.7.5 I switched the repository for AMF to the the 'trunk' repository and now it works. There was a bug in Zend_Amf_Server when sending Arrays over to it.

Categories