Parsing PHP in ActionScript returns "undefined" - php

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.

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(...).

Unable to send data using POST in Python

I am trying to send data using POST from StachExchange API. I am not sure what seems to be the problem. I have checked the script, it's working fine when I try to POST data some other way. The problem seems to be with the python script. The scripts gets the data from the API but doesn't seems to be posting to "generate.php" Nonetheless here's the code:
#!/usr/bin/env python
import requests, json
userinput = input('Enter a keyword: ')
userinputq = input('Enter page: ')
getparams = {'page':userinputq, 'pagesize':'100', 'order':'desc', 'sort':'votes', 'intitle':userinput, 'site':'stackoverflow', 'filter': '!5-HwXhXgkSnzI0yfp0WqsC_-6BehEi(fRTZ7eg'}
r = requests.get('https://api.stackexchange.com/2.2/search', params=getparams)
result = json.loads(r.text)
if result['has_more'] == False:
print("Error given.")
else:
for looping in result['items']:
if looping['is_answered'] == True:
try:
newparams = {'order':'desc', 'sort':'votes', 'site':'stackoverflow', 'filter': '!4(Yrwr)RRK6oy2JSD'}
newr = requests.get('https://api.stackexchange.com/2.2/answers/'+str(looping['accepted_answer_id']), params=newparams)
newresult = json.loads(newr.text)
titletopost = 'Title:', looping['title']
bodytopost = '<h1>Question:</h1><br>'+(looping['body'])+'<br>'+'Link to Question: '+(looping['link'])+'<br><br><br>'+'<h1>Answer:</h1><br>'+(newresult['items'][0]['body'])
enterremove = bodytopost.replace('\n', '').replace('\r', '')
print(enterremove)
userdata = {"secret":"Secret", "topic_title":titletopost, "body":enterremove}
requests.post("http://www.example.com/generate.php", data=userdata)
except KeyError: print("No answer ID found.")
print("")
print("")
Can anyone please explain the problem?
Nevermind! There's nothing wrong with the python script. Actually I forgot to change "$_GET" to "$_POST" in 'generate.php' while I was testing it.

PHP not recognising Flash undefined var

I'm having a problem with Flash AS3 and PHP 5.3.29
I have a var that I want to pass to PHP. This var will in certain cases be undefined or will have a value.
if(!isset($_POST['varName']) || empty($_POST['varName'])){
$name = ">0";
}
else{
$name = "=".$_POST['varName'];
}
AS3 code:
var myVarsReq:URLRequest=new URLRequest(returnQuery);
var phpMyVarsVar:URLVariables = new URLVariables();
myVarsReq.method = URLRequestMethod.POST;
phpMyVarsVar.varName = varName; //varName = undefined;
myVarsReq.data = phpMyVarsVar;
phpMyVarsVar.sendRequest = "getResults";
I use Charles to trace the outgoing data from Flash and when the varName = undefined PHP !isset() is not picking it up as not being set. If I force the varName varName = "" then the empty() function picks it up fine. Similarly, if I give the varName a value, varName = 44 it all works fine so what am I doing wrong with isset??
OK, I echo'd the $_POST var both before and after !isset. The $POST var according to Flash Charles and the echo before the !isset was undefined, not NULL "" or "undefined", however PHP is seeing it as isset and not !isset... Why PHP is doing this? I don't know but for anyone experiencing the same issue: - my work around was to force the var as "" empty rather than undefined. Its not graceful or ellegant but it works... I'd still love to know why though!
Isset only works if the variable isnt set at all, you probably send an empty or vanName=undefined from action script
maybe just do this
if($_POST['varName']=="undefined" || empty($_POST['varName'])){
$name = ">0";
}
else{
$name = "=".$_POST['varName'];
}
For those hwo are still wondering... After some investigation and assistance from another forum it appears that there is no way that you can send a var that is not set (!isset) from flash to PHP. According to PHP it will always be set one way or another.
My findings: - When myVar is defiend as a number but not given a value
sendVartoPHP.varName = myVar:Number
is seen by PHP as string(3)"NaN"
sendVartoPHP.varName = myVar:int
is seen by PHP as string(1)"0"
sendVartoPHP.varName = myVar:String
is seen by PHP as NULL
sendVartoPHP.varName = myVar
a 'none typed' var is seen by PHP as string(9)"undefined"
sendVartoPHP.varName = ""
is seen by PHP as string(0)
sendVartoPHP.varName
not even setting the var to be sent (as above) is seen by PHP as NULL

AS3 -> PHP Foreign Characters giving incorrect information

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.

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

Categories