variable in flash returning as "undefined" - php

i have a variable in flash that takes its value from a php file using the print function.
The variable is not returning the correct value. It's returning "undefined". I have checked of both flash and php source code for errors, they both seem the be fine.
anyone know what could be causing this?
php print code:
print "return_sponsor=$sponsor";
flash code:
function completeHandler(event:Event):void{
// Clear the form fields
name_txt.text = "";
email_txt.text = "";
MovieClip(parent).gotoAndPlay("finish");
// Load the response from the PHP file
variables.sponny = event.target.data.return_sponsor;

I've not used AS3 in a while, but this might work.
Replace:
variables.sponny = event.target.data.return_sponsor;
With:
var data:URLVariables = new URLVariables(event.target.data);
variables.sponny = data.return_sponsor;

I don't know what type your sponny variable is but that error is generally returned when Flash can't convert types correctly. It happens to me if I am trying to convert a string to a Number or int (or some other numeric type) and there is a non-numeric symbol in the string (so "12a4" would not be able to convert properly for example).
When you are debugging, place event.target.data.return_sponsor in a String variable and check that it is the correct data. If you can't debug, you may have to find a way to show the data on the screen somehow (maybe by printing them to the form?)
name_txt.text = event.target.data.return_sponsor;

Related

base64_decode showing corrupted characters

I am building a hyperlink that includes a base64 encoded set of parameters as shown below:
$params = base64_encode("member_id={$recipient_id}&api_key=".SECRET_KEY);
$link = HOST_ADDRESS."test.php?k=" . $params;
When the link is executed, the following code runs:
// get the encoded string from the link parameter
$link_parm = $_GET['k'];
$link = substr($link_parm, 0);
// url encode the string to ensure all special characters convert properly - attempt to stop errors
urlencode($link);
// decode the rest of the link
$decoded_link = base64_decode($link);
// get the remaining data elements from the link parameter
$msg_data = preg_split( "/[&=]/", $decoded_link);
On occasion, the $msg data is corrupted and looks like this:
member_id=167œÈ&api_key=secretkey
As you can see the member id is corrupted.
Can someone please help me understand what may be causing this?
Thanks.
For starters, there are a few problems with this beside the issue you describe.
What are you trying to do using $link = substr($link_parm, 0);? This could just be written as $link = $link_parm;. Or, you could of course just do $link = $_GET['k']; or even just use $_GET['k'].
urlencode($link); does nothing as you're not catching its result. The argument is not passed by reference.
Your "attempt to stop errors" should probably be handled differently. By throwing an error when you're receiving unexpected input, for instance.

Why is the Actionscript object converting the numeric strings in my php-returned XML output?

I'm sending a POST from flex to my php backend and the php code is returning this back:
<?xml version="1.0" encoding="utf-8">
<rs>
<action>getConfiguration</action>
<num>1</num>
<configuration>
<armed>1</armed>
<threshold>90.0</threshold>
</configuration>
</rs>
That's fine, but when I access the parsed XML fields in my flex return handler through
var o:Object = event.result.rs.configuration;
I see (by stepping with FlashDevelop) that o.threshold is "90" instead of "90.0".
I need the "90.0". Why is this conversion taking place, and how do I stop it?
Thanks for reading, and for any insights you can provide.
4/20/2016 Update:
Thanks for the first wave comments folks, I appreciate it. I didn't want to fix the decimal places, it may be more than 1 place (e.g. 90.25), but I don't want "90.00". I don't need to do any math on it, that's done on a different device, but I do need the .0 instead of numbers like 90.
The 90.0 goes on a form to be edited, and I want it to be a string. I went ahead and tried these:
// fails
var num:Number = Number(event.result.rs.configuration.threshold);
var num2:Number = Number(o.threshold);
var num3:String = Number(o.threshold).toString();
var num4:String = String(o.threshold).toString();
// works
var num5:String = Number(o.threshold).toFixed(1).toString();
Nothing magical happened with Number(), which is expected, since examining the object showed that it held "90". I would have expected that if "90.0" is in the XML and a generic object is used to access it, I'd see a string holding 90.0 (for what it's worth, it's also stored in a MySQL as TINYTEXT, but I don't see why that should matter given the XML output). 90.1 and 90.18 come back as 90.1 and 90.18.
I already knew I could treat it like a string, look for a '.', and if not present, concatenate ".0" to it so that my edit form would show what I want it to. But what is the smarter-than-me entity deciding that my 90.0 string should be stored as 90, and how do I tell it to cut it out?
4/21/2016 Update
After some searching / guessing building from Atriace response, I tried to have a more atomically performed XML parse, with
var dataX:String = new XML(event.message.body).toXMLString();
var xmlDoc:XMLDocument = new XMLDocument(dataX);
var decode:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decode.decodeXML(xmlDoc);
and still, I see that resultObj.rs.configuration.threshhold holds "90". I tried a few variations too, same thing. It was nice to see that event.message.body had the 90.0, and it would be even nicer if something stopped deciding I want it turned into a number instead of a string.
As hard as it may be to swallow, all numerical representations of strings will resolve to the nearest relevant non-zero decimal point. Therefore...
var a:Number = Number("90.010"); // 90.01
var b:Number = Number("90.000"); // 90
var c:Number = Number("00.100"); // 0.1
var x:String = Number("90.000").toFixed(1); // "90.0"
Be aware that this only happens when you cast the String as a Number, which is what you're explicitly doing above. Still, you said this was happening "automatically" when your parser loaded the XML; this is disconcerting. Observe:
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, readXML);
urlLoader.load(new URLRequest("configuration.xml"));
function readXML(e:Event):void {
var datum:XML = new XML(e.currentTarget.data);
}
The result of this load & create operation is as follows:
As you can see, the "90.0" is still there and stored as a String. It should then be a simple matter of using the string in your UI (for the customer), and cast the value as a Number when you want to run calculations on the result.
I'd take a look at that parser of yours. It appears to be doing more than you wanted.

PHP - Script to manipulate/replace function parameters in a PHP file?

I'm writing a script (in PHP) which will go through a PHP file, find all instances of a function, replace the function name with another name, and manipulate the parameters. I'm using get_file_contents() then strpos() to find the positions of the function, but I'm trying to find a good way to extract the parameters once I know the position of the start of the function. Right now I'm just using loop which walks through the next characters in the file string and counts the number of opening and closing parentheses. Once it closes the function parameters it quits and passes back the string of parameters. Unfortunately, runs into trouble with quotes enclosing parentheses (i.e. function_name(')', 3)). I could just count quotes too, but then I have to deal with escaped quotes, different types of quotes, etc.
Is there a good way to, knowing the start of the function, to grab the string of parameters reliably? Thank you much!
EDIT:
In case i didn't read the question carefully, if you want to only get function parameters,you can see these example :
$content_file = 'function func_name($param_1=\'\',$param_2=\'\'){';
preg_match('/function func_name\((.*)\{/',$content_file,$match_case);
print_r($match_case);
but if you want to manipulate the function, read below.
How about these :
read file using file_get_contents();
use preg_match_all(); to get all function inside that file.
please not that i write /*[new_function]*/ inside that file to identify EOF.
I use this to dynamically add/ delete function without have to open that php files.
Practically, it should be like this :
//I use codeigniter read_file(); function to read the file.
//$content_file = read_file('path_to/some_php_file.php');
//i dont know whether these line below will work.
$content_file = file_get_content('path_to/some_php_file.php');
//get all function inside php file.
preg_match_all('/function (.*)\(/',$content_file,$match_case);
//
//function name u want to get
$search_f_name = 'some_function_name';
//
for($i=0;$i<count($match_case[1]);$i++){
if(trim($match_case[1][$i]) == $search_f_name){
break;
}
}
//get end position by using next function start position
if($i!=count($match_case[1])-1){
$next_function= $match_case[1][$i+1];
$get_end_pos = strripos($content_file,'function '.$next_function);
} else {
//Please not that i write /*[new_function]*/ at the end of my php file
//before php closing tag ( ?> ) to identify EOF.
$get_end_pos = strripos($content_file,'/*[new_function]*/');
}
//get start position
$get_pos = strripos($content_file,'function '.$search_f_name);
//get function string
$func_string = substr($content_file,$get_pos,$get_end_pos-$get_pos);
you can do echo $func_string; to know whether these code is running well or not.
Use a real parser, like this one:
https://github.com/nikic/PHP-Parser
Using this library, you can manipulate the source code as a tree of "node" objects, rather than as a string, and write it back out.

json_encode won't escape newlines

Firstly, I have search Stack Overflow for the answer, but I have not found a solution that works.
I am using an MVC framework (yii) to generate some views and throw them in an array. Each view is a card, and I have an array of cards ($deck) as well as an array of arrays of cards ($hands, the list of hands for each player). I'm simply trying to set a javascript variable on the front-end to store the hands created in PHP. My view has, it is worth noting, multiple lines. In fact, my current test view consists only of:
test
test
I therefore used json_encode, but it's giving me the following error when I use $.parseJSON():
Uncaught SyntaxError: Unexpected token t
I read elsewhere that it is required (for whatever reason) to use json_encode twice. I have tried this, but it does not help.
With a single json_encode, the output of echoing $hands (followed by an exit) looks pretty healthy:
[["test\ntest","test\ntest","test\ntest","test\ntest", etc...
But when I do not exit, I get a syntax error every time.
Edit: Here is a sample of my code. Note that $cards is an array of HTML normally, but in my simplified case which still errors, includes only the two lines of 'test' as mentioned above.
$deck = array();
foreach ($cards as $card) {
$deck[] = $this->renderPartial('/gamePieces/cardTest',
array('card'=>$card), true);
}
$hands = Cards::handOutCards($deck, $numCards , $numPlayers);
$hands = json_encode($hands);
echo $hands; exit;
With JavaScript, I am doing the following:
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
It errors on page load.
Any help would be appreciated!
Thanks,
ParagonRG
var hands = $.parseJSON('<?php echo json_encode($hands); ?>');
This will result in something like:
var hands = $.parseJSON('{"foobar":"baz'"}');
If there are ' characters in the encoded string, it'll break the Javascript syntax. Since you're directly outputting the JSON into Javacript, just do:
var hands = <?php echo json_encode($hands); ?>;
JSON is syntactically valid Javascript. You only need to parse it or eval it if you receive it as a string through AJAX for instance. If you're directly generating Javascript source code, just embed it directly.

Problem with mixing Javascript the PHP

I am trying to assign values in javascript assigned from PHP and the use document.write() to output them. The problem is when I do this, a complete blank screen shows up but no errors are ever thrown. But if I take the PHP out and put in a value such as 'ABC' it works. And example of my code can be this:
var comment_text="<?php echo $value['comment_text'];?>";
var bodyelement = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
newdiv.style.textAlign = 'center';
newdiv.style.zIndex = 10001;
newdiv.style.left = (<?php echo $comment_x;?>+getPos('browserwindow',"Left")-23) + 'px';
newdiv.style.top = (<?php echo $comment_y;?>+getPos('browserwindow',"Top")-90) + 'px';
newdiv.style.position = 'absolute';
newdiv.innerHTML = comment_text;
bodyelement.appendChild(newdiv);
I do have an PHP error log and no errors are beign thrown either. The values are retrieved from the database, the probem comes with outputting them.
*UPDATE*
Ok, I had this problem before.
Basically a newline is created like this:
var comment_text="cool Beans
";
I have tried to remove the newline with string replace but doesn't seem to work. Why would a new line like this cause this error?
Your issue is cleary in the output from PHP. If you get a blank page, means you most likely have a PHP issue that is HALTING the processing of said page.
As PHP is parsed before anything is sent to the viewer, this will result in a blank / error page.
When you substitute your $value['comment_text'] for ABC you remove the location that causes the error.
I am going to assume that $value['comment_text'] is either a result of a function, or a Database query, try just outputting the $value['comment_text'] first, then worry about sticking it in JS (which will work if your PHP code works).
As I don't see any of your PHP code, I cannot help you further.
Use
var comment_text=String(<?php echo json_encode($value['comment_text']);?>);
instead of
var comment_text="<?php echo $value['comment_text'];?>";
This will protect you from cross-site-scripting attacks by escaping all special characters like backslashes, quotes or line feeds.
The String(...) ensures that comment_text has type String and is not interpreted as a number (if $value['comment_text'] is has a number type).
If PHP is causing an error (sounds like it is) you can turn on your error reporting to see the issues
error_reporting(E_ALL)
The solution was just using trim.
echo trim($value['comment_text']);
I recommend you use a heredoc for the javascript code with %s in the js. and use sprintf to substitute the variables.

Categories