November 20, 2011 in Actionscript, PHP, Programming, Tutorials by admin

Have you ever wanted to post variables from AS3 to a PHP and get data back from the PHP? This tutorial will show you how to easily take ActionScript 3 variables and post the to PHP. We will create a simple login with AS3 and PHP.

In our ActionScript we will be using urlRequest and URLLoader to send data to a PHP file and retrieve information back into the ActionScript.

In our urlRequest we will first determine the location of our PHP file and then set any variables that we want to send to the PHP. We will add all of our variables to a URLVariables() object and add that to our urlRequest.

We then add our request to the loader and add an event listener to fire on completion. There we will grab our variables that were sent from our PHP file.

JavaScript
1
2
3
4
5
6
7
8
/*recommended imports*/
import flash.display.*;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public function Login():void
{
    // We will use URLRequest to post our variables to a
    // PHP file which will return variables back
    
    // Set the location of your PHP file
    var urlReq:URLRequest = new URLRequest ("login.php");
    
    // Set the method to POST
    urlReq.method = URLRequestMethod.POST;
    
    // Define the variables to post    
    var urlVars:URLVariables = new URLVariables();
    urlVars.userName = 'myUsername';
    urlVars.userPass = 'myPassword';
    
    // Add the variables to the URLRequest
    urlReq.data = urlVars;
                
    // Add the URLRequest data to a new Loader
    var loader:URLLoader = new URLLoader (urlReq);
    // Set a listener function to run when completed
    loader.addEventListener(Event.COMPLETE, onLoginComplete);
    // Set the loader format to variables and post to the PHP
    loader.dataFormat = URLLoaderDataFormat.VARIABLES;
    loader.load(urlReq);
}
public function onLoginComplete(event:Event): void
{
    //retrieve success variable from our PHP
    if(event.target.data.success == "true"){
        trace("Login Complete");
    }
}

In our PHP file we can grab our variables and handle them in PHP. This makes it easy to create sessions and store in the database. Using GET parameters we can return variables back to our ActionScript file.

Save this as your login.php

PHP
1
2
3
4
5
6
7
8
9
<?php
    //Grab username and password variables
    $username = $_POST['userName'];
    $password = $_POST['userPass'];
    
    // for additional variables use the &
    // success=true&username=$username&password=$password
    echo "success=true";
?>