This tutorial will demonstrate how to create simple but professional Flash login system using three different programming languages; AS3, PHP and MYSQL. Advanced sections like application logic, PHP and MYSQL integration with Flash will be our main talking points. Let's get stuck in!



Let's take a look at the final result, simply click the demo button at the top of this tutorial.
Try logging in with the username admin and password password, or username test1 and password password1. You'll see a simple piece of text corresponding to that user.
In this Part we'll get the actual login working, then in Part 2 we'll let users register through a SWF.

If you do not have web server that supports mysql databases and php, then download MAMP (for Mac), WAMP (for Windows), or another local server.
MAMP is an open source local server that allows you to run php and create and store data in mysql databases from your local hard drive. MAMP automatically creates a server when you download it therefore I recommend using it over other local servers.
You can alternatively use your web server if it supports mysql and php.
Install phpMyAdmin on the server, we will use it later.

Here are the things you will need in order to create the end product.
  • A text or html editor (for example notepad or Dreamweaver).
  • Flash CS3+
Now we have everything we need it is time to set up our document class.

Create a brand spanking new .as file and an AS3 .fla file. Save the .as file as main.as in a new folder called actions.
Save the fla file in the root folder of our application. Now in our .fla file enter the main class name (and classpath) in the properties panel, as stated below:

Open your main.as file and add the following code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package actions {
     
    /*
    always extend a class using movieclip instead of sprite when using flash.
    */
    import flash.display.MovieClip;
     
    /*
    create our class
    */
     
    public class main extends MovieClip {
         
        public function main ():void {
         
            trace("success");
         
        }
     
    }
}
This will be your document class. Press ctrl+enter to run the SWF.
If you get a message in the output you have successfully connected both documents and can move on.

To create a connection to our database we need to use php. First you need to create a database on your server. Call it admin. You can create a database using phpMyAdmin on your server. The image below is first page you see when opening phpMyAdmin. This is the only time we will be using phpMyAdmin; we will be creating the table using php.

We need one file that will connect to our database. Create a new folder called php. Create a new document with the php extension and call it connect.php
Follow the code comments to see what's going on.
01
02
03
04
05
06
07
08
09
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
/*
All code inside these tags will be recognized as php code.
*/
<?php
/*
Database vars that we use to connect to our mysql database. Change the values to your database settings.
*/
$db_name = "admin";
$db_username = "root";
$db_password = "root";
$db_host = "localhost";
/*
mysql_connect is a built in function that allows us to make an easy connection.
*/
mysql_connect($db_host, $db_username, $db_password, $db_name);
/*
mysql_select_db is a built in function that allows us to select the database. This is an essential function.
We use the 'die' function to check for errors.
*/
mysql_select_db($db_name) or die (mysql_error());
echo 'success';
?>
Then you need to upload your files to the testing server. If you are using MAMP copy your folder to the htdocs folder in the mamp application folder.
If there is a successful connection there will be a success message as below and you'll have connected to your database.
Note: It is important to delete echo 'success'; from your PHP afterwards.
Note: The directory will not be the same as in the image. Ignore the "source" path. For example http://localhost:8888/loginsystem/php/connect.php

First Create Two Text Boxes - Input Text - to allow the user to enter their name and password.
Then position them vertically. Give the top textbox the instance name of "username" and the bottom one "password". Label the two any way you want.
Then draw a square and insert another text box writing in it "submit". Convert these to a movie clip with an instance name of "submit_button".
Distribute all different objects to layers (Modify > Timeline > Distribute to Layers).
Your interface should look something like this:

Next we will create our submit button event handler, checkLogin(), to be run when the user clicks "submit".
First we need to import flash.events.*; in our code. This way we can use Flash events. Follow the code comments.
01
02
03
04
05
06
07
08
09
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package actions {
     
    /*
    always extend a class using movieclip instead of sprite when using flash.
    */
    import flash.display.MovieClip;
    import flash.events.*;
     
    /*
    create our class
    */
     
    public class main extends MovieClip {
         
        public function main ():void {
            /*
            buttonMode gives the submit button a rollover
            */
             
             
            submit_button.buttonMode = true;
            /*
            what this says is that when our button is pressed, the checkLogin function will run
            */
            submit_button.addEventListener(MouseEvent.MOUSE_DOWN, checkLogin);
            /*
            set the initial textfield values
            */
             
            username.text = "";
            password.text = "";
         
        }
        /*
        the function to checkLogin
        */
         
        public function checkLogin (e:MouseEvent):void {
         
            trace("submission success");
         
        }
     
    }
}
If the output displays "submission success" when you click the button, our button event has been created successfully.

Now we are going to check whether our fields have data. Replace the current checkLogin function with the code below. It's thoroghly commented for your convenience.
01
02
03
04
05
06
07
08
09
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
38
39
/*
the function to check login
*/
public function checkLogin (e:MouseEvent):void {
    /*
    check fields before sending request to php
    */
     
    if (username.text == "" || password.text == "") {
         
        /*
        if username or password fields are empty set error messages
        */
         
        if (username.text == "") {
         
        username.text = "Enter your username";
         
        }
         
        if (password.text == "") {
         
        password.text = "Enter your password";
         
        }
     
    } else {
         
        /*
        init function to process login
        */
     
        processLogin();
     
    }
}

Data is stored in tables in databases. Therefore we will need to create a table and we'll use php to do so. Create a new php document in the php folder and call it whatever you want (it won't matter, this is just temporary to create the table, we won't need to keep running it). Then fill it with the code below.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
/*
connect to our database
*/
require_once "connect.php";
/*
create the mysql query
*/
$sql = "CREATE TABLE users (
                             
        id int(11) NOT NULL auto_increment,
        username varchar(255) NOT NULL,
        password varchar(255) NOT NULL,
        user_bio longtext NOT NULL,
        PRIMARY KEY (id)
         
        )";
$query = mysql_query($sql);
if ($query === TRUE) {
echo 'You have successfully created your table';
}
mysql_close();
?>
After this, upload all your files to your server. Then enter the file path into the browser, if the table was created it will display a success message. If not, then please check your configuration. Note: Make sure you delete this file from the server after the success message is displayed.
Then go to phpMyAdmin or an alternative to check whether your table has been added. If it has been added this is what you will see below...

Now we have our table created let's go ahead and add a user.
Create a new php document and call it whatever you like, then place it in the php folder.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
/*
connect to the database
*/
require_once "connect.php";
/*
create the mysql query
What this query means is php calls mysql to insert values into the table users. It then asks for the fields you want to add data too then the values for that certain field in ascending order.
*/
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('admin', 'password', 'This is the user bio')";
$query = mysql_query($sql);
mysql_close();
?>
We have now added a user so therefore our table will look like this:
We should be all set to start creating our application logic, which will power the backend of our SWF.

There a few variables we need to process in order to get our database data.
Here is the completed processLogin() function, to go in our main.as file (it will be called when the user clicks the button). We need to import Flash's net classes here. So, add this at the top: import flash.net.*;
01
02
03
04
05
06
07
08
09
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
function to process our login
*/
public function processLogin ():void {
     
    /*
    variables that we send to the php file
    */
    var phpVars:URLVariables = new URLVariables();
     
    /*
    we create a URLRequest  variable. This gets the php file path.
    */
     
    var phpFileRequest:URLRequest = new URLRequest("php/controlpanel.php");
     
    /*
    this allows us to use the post function in php
    */
     
    phpFileRequest.method = URLRequestMethod.POST;
     
    /*
    attach the php variables to the URLRequest
    */
     
    phpFileRequest.data = phpVars;
     
    /*
    create a new loader to load and send our urlrequest
    */
     
    var phpLoader:URLLoader = new URLLoader();
    phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;  
    phpLoader.addEventListener(Event.COMPLETE, showResult);
     
    /*
    now lets create the variables to send to the php file
    */
     
    phpVars.systemCall = "checkLogin";
    phpVars.username = username.text;
    phpVars.password = password.text;
     
    /*
    this will start the communication between flash and php
    */
     
    phpLoader.load(phpFileRequest);
}

The first line:
1
phpVars.systemCall = "checkLogin";
will be explained later when we create the main php control file.
The next two lines:
1
2
phpVars.username = username.text;
phpVars.password = password.text;
retrieve what the user inputted into the two text fields and convert them into php variables.

Create a dynamic text box and give it an instance name of "result_text".
Place it under the login form and submit button. This will display information retrieved from the server.

This is the file that will communicate with php and return a value to flash. Create a new php file called "controlpanel.php" and place it in the \php\ folder.
01
02
03
04
05
06
07
08
09
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
/*
connect to our database
*/
include_once "connect.php";
/*
we post the variables we recieve from flash
*/
$username = $_POST['username'];
$password = $_POST['password'];
/*
if flash called the login system the code below runs
*/
if ($_POST['systemCall'] == "checkLogin") {
     
/*
The * means the query initally selects all the records in the database.
Then the query filters out any records that are not the same as what the user entered.
*/
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$query = mysql_query($sql);
/*
This counts how many records match our query
*/
$login_counter = mysql_num_rows($query);
/*
if $login_counter is greater we send a message back to flash and get the data from the database
*/
if ($login_counter > 0) {
/*
we use a while loop to get the user's bio. mysql_fetch_array gets all the field's data for the particular record.
*/
while ($data = mysql_fetch_array($query)) {
     
/*
gets the user_bio value from the selected record
*/
$userbio = $data["user_bio"];
/*
use the print function to send values back to flash
*/
print "systemResult=$userbio";
}
} else {
print "systemResult=The login details dont match our records.";
}
}
?>

Let's go back to our process login function and add this:
1
phpLoader.addEventListener(Event.COMPLETE, showResult);
When the form has finished this listener calls the showResult() function. We will look at that now.

Here is the function. It displays the value we printed in the "controlpanel.php" file.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
function to show the result of the login
*/
public function showResult (event:Event):void {
     
    /*
     
    this autosizes the text field
     
    ***** You will need to import flash's text classes. You can do this by adding:
     
    import flash.text.*;
     
    ...to your list of import statements
     
    */
     
    result_text.autoSize = TextFieldAutoSize.LEFT;
     
    /*
    this gets the output and displays it in the result text field
    */
     
    result_text.text = "" + event.target.data.systemResult;
}
The SWF is getting the text that we print in the php and displaying it in the result_text textfield.

If you have created a successful login, this is what you will see:
Now we are going to add an additional user to test whether our system works for multiple users.

Open the "adduser.php" file in our php folder that we created earlier.
Simply change the VALUES in the mysql query.
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('test1', 'password1', 'This is the additional users bio')";
Then run the script on the server by simply entering the file path in a web browser.

Success! We have a successful flash login system that supports multiple users. Here is the result when we login the additional user.

Advertisement

Well that concludes Part 1 of our Flash login system tutorial. In Part 2 we will be creating a registry form that will add users without the user entering it in the backend. Thanks for reading this tutorial. Enjoy it :)
 
Top