Loading PHP URL in Flash AS3 - php

I am working on an online game in Flash AS3 and utilizing a PHP server with mySQL database. I am manipulating the data in mySQL database using PHP and when I request the PHP file in a browser straightly from 'localhost/php/file.php', the database changes perfectly. I have the following AS3 code:
public function getSite(string):Boolean{
var phpVars:URLVariables = new URLVariables();
var t:Boolean = false;
/*
we use the URLRequest method to get the address of our php file and attach the php vars.
*/
var urlRequest:URLRequest = new URLRequest(string);
/*
the POST method is used here so we can use php's $_POST function in order to recieve our php variables.
*/
urlRequest.method = URLRequestMethod.POST;
/*
this attaches our php variables to the url request
*/
urlRequest.data = phpVars;
/*
we use the URLLoader class to send the request URLVariables to the php file
*/
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, check(t));
t = check(t);
/*
runs the function once the php file has spoken to flash
*/
/*
we send the request to the php file
*/
urlLoader.load(urlRequest)
return t;
}
function check(t:Boolean):Function{
return function (event:Event):Boolean{
trace(event.target.data.checkResult);
if(event.target.data.checkResult == "Good"){
t = true;
} else {
t = false;
}
return t;
}
}
Now from here, my "trace" shows that the URL is loaded and the output is "Good", however the database values does not change. This is the PHP file:
<?php
/*
connect to our database
*/
include_once "connect.php";
$sql = "UPDATE accounts SET PlayersOnline = accounts.PlayersOnline + 1";
$query = mysql_query($sql) or exit("checkResult=Bad");
exit("checkResult=Good");
?>
When I go to 'localhost/php/gameSearch.php' in my web browser the database changes, and I am wondering what the problem is.

You have a "caching" problem. In other words, the result of the already requested URL is cached to reduce latency and access times, and what you've represented is the cached copy of the output and not a fresh output resulting from the execution of the instructions on behalf of the server.
To overcome the issue, you could've pushed a no-cache header to the requestHeaders property on your "request" object (the property is of type URLRequestHeader). However, the runtime looks to be ignorant on the header and it always provides the cached copy!
To overcome that issue, however, you need to fool the runtime as if you are requesting a new URL every time by appending a dummy random-valued variable:
getSite("localhost/php/file.php?r="+Math.random());
And regarding your specific provided code; The URLLoader works asynchronously, that's why you register a "on complete" listener! The t = check(t); statement induces you're attempting to "check" the result while it may not be ready by then! You should check it when/after the listener triggered. In addition to the fact that the assignment is syntactically inappropriate (assigning a Function to a Boolean!) and reconsider the logic of the check function!
And in the PHP code, as others have suggested, ultimatly don't use the deprecated mysql_query function and use a more appropriate API.

Related

download values of sql table for offline reuse

I've got a Flash app that calls an online php file in order to read some values of my SQL table.
So I've got a line like this in my AS3 code:
var urlReq:URLRequest = new URLRequest ("http://www.****.com/sql_result.php");
And this in my php :
$connection = mysql_connect("mysql***.perso", "test", "password") or die ("Couldn't connect to the server.");
Problem : if the user is offline he can't access the values.
Is there way to download the SQL table with AS3 code (when the user have internet) in order to access it offline.
Like :
function onConnection(e:Event = null):void{
if(monitor.available)
{
trace("You are connected to the internet");
read_php_online();
}
else
{
trace("You are not connected to the internet");
read_php_offline();
}
monitor.stop();
}
function read_php_offline():void{
var urlReq:URLRequest = new URLRequest ("local/sql_result_offline.php");
..
..
}
And what should have sql_result_offline.php in order to access an offline SQL Table ?
$connection = mysql_connect("LOCAL", "user", "password");
Thank you,
For FLASH :
To save data locally with flash, you can use one of 3 manners : the Flash Player cache, a SharedObject, or a FileReference object. And for your local file, forget PHP and MySQL because we are speaking only about the data that you got ( json, xml, txt, ... ).
- Flash Player cache :
You should know that by default, flash player put a local copy of your file in its cache. You can use this local copy as an offline source of your data, but here don't forget that flash player didn't save the last version of your remote file but the first one and that http://www.example.com/data.php is different from http://www.example.com/data.php?123 even if it's the same file ! For more details about that, take a look on my answer of this question.
- SharedObject :
I don't know the size of your loaded data, but as Adobe said about SharedObject :
... is used to read and store limited amounts of data on a user's computer ...
I think that is not used for large files and it's not recommended to store files but some simple data. Of course, as a cookie for the browser, SharedOject needs user's authorization to write data to the hard drive, and user can delete it at any time.
- FileReference :
I think this is the best manner to do what you are looking for. You should know that to save a file using FileReference, your user is invited to select a file for saving data and reading it in a second time. So if you don't want any user's interaction with your application, forget this manner.
FileReference using example :
var local_file_name:String = 'local.data',
file:FileReference = new FileReference(),
local_file_filter:FileFilter = new FileFilter('local data file', '*.data'),
remote_data_url:String = 'http://www.example.com/data.php',
url_request:URLRequest,
url_loader:URLLoader,
connected:Boolean = true;
if(connected){
get_remote_data();
} else {
get_local_data();
}
function get_remote_data(): void {
//we use a param to be sure that we have always the last version of our file
url_request = new URLRequest(remote_data_url + ('?' + new Date().getTime()));
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, on_data_loaded);
url_loader.load(url_request);
}
function get_local_data(): void {
// show the select dialog to the user to select the local data file
file.browse([local_file_filter]);
file.addEventListener(Event.SELECT, on_file_selected);
}
function on_data_loaded(e:Event): void {
var data:String = e.target.data;
// if the remote data is successfully loaded, save it on a local file
if(connected){
// show the save dialog and save data to a local file
file.save(data, local_file_name);
}
// use your loaded data
trace(data);
}
function on_file_selected(e:Event): void {
file.addEventListener(Event.COMPLETE, on_data_loaded);
file.load();
}
This code will show every time a save dialog to the user, of course, it's just a sample, you have to adapt it to your needs ...
EDIT
For AIR :
With AIR we don't need a FileReference object, instead we use File and a FileStream object to save data :
// for example, our local file will be saved in the same dir of our AIR app
var file:File = new File( File.applicationDirectory.resolvePath('local.data').nativePath ),
remote_data_url:String = 'http://www.example.com/data.php',
data_url:String = remote_data_url,
url_request:URLRequest,
url_loader:URLLoader,
connected:Boolean = true;
if(!connected){
// if we are not connected, we use the path of the local file
data_url = file.nativePath;
}
load_data();
function load_data(): void {
url_request = new URLRequest(data_url);
url_loader = new URLLoader();
url_loader.addEventListener(Event.COMPLETE, on_data_loaded);
url_loader.load(url_request);
}
function on_data_loaded(e:Event): void {
var data:String = e.target.data;
if(connected){
// save data to the local file
var file_stream:FileStream = new FileStream();
file_stream.open(file, FileMode.WRITE);
file_stream.writeUTFBytes(data);
file_stream.close();
}
trace(data);
}
Hope that can help.
you have a flash swf, mobile app or air app?
Storing local data
you can use file as database (like csv), for mobile and air you can use local SQLite database.
if you have native desktop app - it is possible to use mysql, via native process or native extension but it is not so easy..
edit:
Working with local SQL databases in AIR [+] you can keep your data safe- with encryption, a password at startup and etc. [-] it will require a lot more of code (create database after install, sync regularly, get data from local database if no internet conn.) mysql and sqlite have some differences also (like "insert or update" statement for sqlite)

Can I run asp.net code on a PHP server?

I have a domain using Php but I added asp.net code. And try to execute that it displayed asp.net code only. Whether it is possible to add asp.net code under php domain by using any plugin or some third party help. If yes means, give some idea.
You could use HttpWebRequest to get a result off a PHP page which might help you a bit. An example taken from: https://stackoverflow.com/a/9818700/4068558
string myRequest = "abc=1&pqr=2&lmn=3";
string myResponse="";
string myUrl = "Where you want to post data";
System.IO.StreamWriter myWriter = null;// it will open a http connection with provided url
System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(myUrl);//send data using objxmlhttp object
objRequest.Method = "GET";
objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(myRequest);//send data
myWriter.Close();//closed the myWriter object
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
myResponse= sr.ReadToEnd();
}
Otherwise, the problem is IIS will see a .php file and compile it with PHP. Vice versa with ASP. Although a work around for running PHP inside ASP.NET is phalanger.

Unknown error communicating between PHP and Actionscript

I've got a problem that's either insanely simple or complex, it's up to you to find out. I've been working on trying to incorporate the URL Loader class into the beginners graphics program - Stencyl. I am fluent in HTML, CSS and PHP but actionscript is completely new to me so I really could use with a hand. Here's what I've got:
There are 4 files hosted on my domain:
Webpage.html
Stylesheet.css
RequestData.php
FlashDoc.swf
The html and css code is simple, no problems there and the swf file embed in the html document. The flash file is a simple form with a text field, submit button and two dynamic text fields. The code goes as follows:
// Btn listener
submit_btn.addEventListener(MouseEvent.CLICK, btnDown);
// Btn Down function
function btnDown(event:MouseEvent):void {
// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();
// Build the varSend variable
// Be sure you place the proper location reference to your PHP config file here
var varSend:URLRequest = new URLRequest("http://www.mywebsite.com/config_flash.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;
// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);
variables.uname = uname_txt.text;
variables.sendRequest = "parse";
// Send the data to the php file
varLoader.load(varSend);
// When the data comes back from PHP we display it here
function completeHandler(event:Event):void{
var phpVar1 = event.target.data.var1;
var phpVar2 = event.target.data.var2;
result1_txt.text = phpVar1;
result2_txt.text = phpVar2;
}
}
I then have a small PHP file with this code:
<?php
// Only run this script if the sendRequest is from our flash application
if ($_POST['sendRequest'] == "parse") {
// Access the value of the dynamic text field variable sent from flash
$uname = $_POST['uname'];
// Print two vars back to flash, you can also use "echo" in place of print
print "var1=My name is $uname...";
print "&var2=...$uname is my name.";
}
?>
This is, for some reason, not working. The result is just two blank text fields and being an actionscript noob, I have no idea what is up. Any help would be greatly appreciated. Thank you for your time.
The answer to your issue is both simple and surprising, if you're not used to AS3.
In AS3, the flash.* classes tend to, when a setter is used, make and store a copy of the passed object.
Since they store a copy, any modification on the original instance after the setter isn't applied on the copy, and thus is ignored.
It is the case of, for example, DisplayObject.filters, ContextMenu.customItems or URLRequest.data.
In your code, you are setting varSend.data = variables before filling variables. You should do the reverse :
variables.uname = uname_txt.text;
variables.sendRequest = "parse";
varSend.data = variables;
// Send the data to the php file
varLoader.load(varSend);
Only some classes do that, and even then, they usually don't do it with all of their setters.

Retrieving Information from MySQL via PHP to AS3

I am currently doing a tutorial which was found on TutsPlus.
This tutorial was to save information from AS3 to MySQL via PHP and then retrieve this information.
So far, it works. I Can enter a username and score, which saves to the database. There is one problem though, I would like to be able to display ALL the names and scores in a table, instead of having to search for a name and then finding the score for that specific user.
The code in which the information is saved (which works), is below.
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class register extends MovieClip {
public function register ():void {
register_button.buttonMode = true;
register_button.addEventListener(MouseEvent.MOUSE_DOWN, checkForm);
username_text.text = "";
userbio_text.text = "";
}
public function checkForm (e:MouseEvent):void {
if (username_text.text != "" && userbio_text.text != "") {
sendForm();
} else {
result_text.text = "PLEASE ENTER A NAME";
}
}
public function sendForm ():void {
/*
we use the URLVariables class to store our php variables
*/
var phpVars:URLVariables = new URLVariables();
phpVars.username = username_text.text;
phpVars.userbio = userbio_text.text;
/*
we use the URLRequest method to get the address of our php file and attach the php vars.
*/
var urlRequest:URLRequest = new URLRequest("localhost/php/register.php");
/*
the POST method is used here so we can use php's $_POST function in order to recieve our php variables.
*/
urlRequest.method = URLRequestMethod.POST;
/*
this attaches our php variables to the url request
*/
urlRequest.data = phpVars;
/*
we use the URLLoader class to send the request URLVariables to the php file
*/
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
/*
runs the function once the php file has spoken to flash
*/
urlLoader.addEventListener(Event.COMPLETE, showResult);
/*
we send the request to the php file
*/
urlLoader.load(urlRequest);
}
/*
function to show result
*/
public function showResult (e:Event):void {
result_text.text = "" + e.target.data.result_message;
}
}
}
From here, I can go to another application and search the users name, and then displays that users score. Code below:
package actions {
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.text.*;
public class main extends MovieClip {
public function main ():void {
submit_button.buttonMode = true;
submit_button.addEventListener(MouseEvent.MOUSE_DOWN, checkLogin);
username.text = "";
}
public function checkLogin (e:MouseEvent):void {
if (username.text == "") {
username.text = "Enter your username";
}
else {
processLogin();
}
}
public function processLogin ():void {
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest("http://xx.xx.xx.uk/~bf93fv/Source%202/php/controlpanel.php");
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpLoader.addEventListener(Event.COMPLETE, showResult);
phpVars.systemCall = "checkLogin";
phpVars.username = username.text;
phpLoader.load(phpFileRequest);
}
public function showResult (event:Event):void {
result_text.autoSize = TextFieldAutoSize.LEFT;
result_text.text = "" + event.target.data.systemResult;
}
}
}
The controlpanel.php file, which displays the username and score individually is below:
<?php
include_once "connect.php";
$username = $_POST['username'];
if ($_POST['systemCall'] == "checkLogin") {
$sql = "SELECT * FROM users WHERE username='$username'";
$query = mysql_query($sql);
$login_counter = mysql_num_rows($query);
if ($login_counter > 0) {
while ($data = mysql_fetch_array($query)) {
$userbio = $data["user_bio"];
print "systemResult=$username Scored $userbio";
}
}
else {
print "systemResult=The login details dont match our records.";
}
}
?>
Does anybody know any easy way in order to view ALL the information from the database into a table?
There are few things you might want to improve in your PHP code (your AS3 is better).
Use PDO instead of the functions that work with particular DBMS. The reason to this is that it is portable (to an extend). Say, if you wanted to ever move the database from MySQL to Postgres, you'd had to rewrite less of your code, then you would have to otherwise. PDO also provides some means of sanitizing the input. It's not bullet proof - still better then nothing. PDO is considered the "good practice", so you would learn to write the good code right away instead of making that journey from writing newby-style code at first and then discovering how to actually do it properly. It might be just a little bit more verbose if you are thinking about a very primitive task such as a single select, but as soon as your task becomes just a little bit more complex it becomes all worth the time.
In your SQL queries make a general rule never to use select *, unless for testing / debugging. That's sort of laziness that in the end will cost you a lot of problems. By doing so you will make it very difficult to maintain your code later, effectively transforming it into "write once - run away" kind of thing. Again, as a simple proof of concept it is OK, - long-term solution - bad. If you are still blur on what I'm trying to say: list all column names explicitly.
Using include / require and their _once family is a bad idea as a long-term solution. Again, OK for a simple test - bad in the long run. Good programs are written in functions / classes and use __autoload() or a framework that uses the ability to load classes automatically. This makes larger applications more manageable, easier to navigate and understand then the web of includes.
You must sanitize input from the user of your web application, that is don't do $_POST['key']. At least write the function that will both check that the key exists and that it is of an expected format.
Now, your actual problem, sending the data.
You can just send the raw SQL output you get in PHP - will spare your server the problem of re-encoding all of it. Works in the very simple cases, but it becomes more complex with more complex tasks. This is also uncommon to do, so you will find that people will not know how to handle that. (No technical restriction, it is just really a historical artefact).
There are a bunch of popular formats that can be digested by variety of applications, not necessary Flash. Those include XML, JSON, Protobuf. There are also some more particular to PHP like the one produced from serialize(). I'd urge you to stick to JSON if you go down this route. XML might be a more mature technology, but JSON has a benefit of the basic type system built in (while in XML it is yet another layer on top of it, which is, beside other things is not implemented in Flash - I'm talking about XSL).
There's AMF (ActionScript Message Format) - it is ideal for Flash. PHP also knows very well how to produce it (there are several popular implementations out there). This format is a lot more compact compared to JSON or XML. It has more expressive power (can describe circular dependencies, many-to-many relationships, has a procedure for introducing custom types, custom [de]serialization routines). It is also self-describing, unless you used custom serialization routine. This is the best option if you aren't planning on moving your application to JavaScript later, because JavaScript has problems consuming binary data. Parsing this format would not be possible there.
Protobuf is a viable option too. This is a data exchange format designed by Google. It is similar in spirit to AMF, however it may not be self-describing. It relies on the application to know how to produced custom objects from it. It has, however, a form, that can be parsed in JavaScript (although you'd lose the the compactness benefit).
Your ActionScript code: If you opt for AMF, you'd need to look into NetConnection class. I'd advise you to take a look in AMFPHP project - it also has examples. Alternatively, Zend Framework has Zend_Amf library to be used for that purpose. But using the entire framework may be overwhelming at start.
If you go with XML - then there's a built-in XML class, there are millions of examples on the web on how to use it.
If you go with JSON, then since not so long ago there's a built-in class for that too. But before there was one, there were several libraries to parse it.
There used to be a project on GoogleCode for Protobuf support in Flash, but it required quite a bit of acquittance and manual labour to get going.
Finally, index of things mentioned here:
http://php.net/manual/en/book.pdo.php - PDO
http://php.net/manual/en/function.json-encode.php - JSON in PHP
http://php.net/manual/en/book.dom.php - XML in PHP (There is no agreement on which XML library is better if PHP is considered. I'd probably stick to this, but ymmv).
http://www.silexlabs.org/amfphp/ - AMF in PHP
http://framework.zend.com/manual/1.12/en/zend.amf.html Zend_Amf library
http://code.google.com/p/protobuf-actionscript3/ Protobuf in ActionScript
https://github.com/drslump/Protobuf-PHP PHP Protobuf (sorry, never used this one, but looks fine)
http://www.blooddy.by/en/crypto/ for older versions of Flash player - this library has the best JSON decoder I know of.
The best way is (I think) to use XML.
On the PHP side, the script output an XML document with all the users :
$sql = "SELECT * FROM users "; // add order statement if needed
$query = mysql_query($sql);
$login_counter = mysql_num_rows($query);
$xml = array('<?xml version="1.0" encoding="UTF-8"?><users>');
if ($login_counter > 0) {
while ($data = mysql_fetch_array($query)) {
$xml[] = '<user name="'.$data['username'].'" bio="'.$data["user_bio"].'" />';
}
}
else {
// do nothing
// you will handle it on the flash side by checking the length of user nodes list
}
$xml[] = '</users>';
header('Content-Type:text/xml');
die(implode('', $xml));
This will output an XML document :
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user name="..." bio="..." />
<user name="..." bio="..." />
[...]
</users>
(There are class on PHP like SimpleXML to deal with XML in a cleaner way)
AS Side :
You can easily browse / display the data on the flash side with the help of the XML / XMLList class
Just adapt the URLLoaderDataFormat to TEXT and convert the data to XML in the complete event handler :
var xml:XML = new XML(event.target.data);
Then iterate the user elements to display them :
var users:XMLList = xml.user;
var user:XML;
for (user in users) {
trace('name->' + user.attribute('name') );
trace('bio->' + user.attribute('bio') );
}

AS3 and mySQL or XML: Saving user votes on server from a flash movie

A project of mine involves a flash movie (.swf) in a webpage, where the user has to pick from a number of items, and has the option to thumbs up or thumbs down (vote on) each item.
So far I have gotten this to work during each run of the application, as it is currently loading the data from an XML file - and the data is still static at the moment.
I need to persist these votes on the server using a database (mySQL), such that when the page is reloaded, the votes aren&apos;t forgotten.
Has anyone done this sort of thing before?
The two mains methods that I have found on the &apos;net are
either direct communication between AS3 and the SQL using some sort of framework, or
passing the SQL query to a PHP file, which then executes the SQL query and returns the SQL to AS3.
Which of these methods is the better option?
For the latter method (involving PHP), I have been able to find resources on how to acheive this when attempting to retrieve information from the database (i.e. a read operation), but not when attempting to send information to the database (i.e. a write operation, which is needed when the users vote). How is this done?
Thank you!
Edit: Implemented solution
Somewhere in the PHP file:
if ($action == "vote")
{
$id = $_POST['id'];
$upvotes = $_POST['upvotes'];
$query = "UPDATE `thetable` SET `upvotes` = '$upvotes' WHERE `thetable`.`id` = '$id' LIMIT 1 ;";
$result = mysql_query($query);
}
Somewhere in the ActionsScript:
public function writeToDb(action:String)
{
var loader:URLLoader = new URLLoader();
var postVars:URLVariables = new URLVariables();
var postReq:URLRequest = new URLRequest();
postVars.action = action;
postVars.id = id;
postVars.upvotes = upvotes;
postReq.url = <NAME_OF_PHP_FILE>;
postReq.method = URLRequestMethod.POST;
postReq.data = postVars;
loader.load(postReq);
loader.addEventListener(Event.COMPLETE, onWriteToDbComplete);
}
I am not aware of any framework that supports method-1.
I would use method-2 - but instead of making the query within Flash and passing it to PHP, I would rather pass the related data and construct the query in PHP itself. This is safer because it is less susceptible to SQL injection attacks.
This answer has an example of sending data from flash to the server - it talks about ASP, but the method is same for PHP (or any technology) - just change the URL.
Within the php code, you can read the sent data from the post $_POST (or $_GET) variable.
$something = $_POST["something"]
Many different options:
AMFPHP - binary messaging format between PHP and Actionscript/Flash.
LoadVars - for POSTing and GETing values to a PHP script.
JSON - Using the AS3Corelib you can post JSON formatted data to your web site (just like an AJAX script does).

Categories