Create a Flash Login System Using PHP and MySQL – Part 2

Create a Flash Login System Using PHP and MySQL – Part 2

Tutorial Details
  • Difficulty: Advanced
  • Program: Flash
  • Estimated Completion Time: 40 mins

In Part 1 we created the front end login system for users to enter their details. In this tutorial we will create a registry form that will allow users to register. This will then add their details to the database, after which they will be able to login.


Step 1: Setup Document Class

Firstly, let’s setup our document class and Flash file. Open a new Flash file, then call it register.fla. Next, create an actionscript file and call it register.as

Then type register in the class text field in the Properties panel.


Step 2: Setup Code Structure

Now we have connected our document to our code, we need to create our class in the as file.

package {

	import flash.display.*;

	public class register extends MovieClip {
	
		public function register ():void {
		
			trace("success");
		
		}
	
	}

}

Step 3: Create The Registry Form Interface

Draw a 460x300px filled rectangle and choose what background color you like. Create the title – Register With Us – and a text field – Register.

Your interface should look like this:


Step 4: Setup The Form Fields

Create three input text fields with the instance names of username_text, password_text and userbio_text.


Step 5: Create The Register Button

Click the text field with “Register” that you created in Step 3 and convert it to a movie clip. Give it an instance name of register_button.

By now your interface should look like this:


Step 6: Create The Result Text

Create a new dynamic textfield next to the register and give it an instance name of result_text. We have completed all the objects we need. Our finished interface should look like this.


Step 7: Get Assets From Part 1

To save you time I will not cover the connection in this Part as you can learn that in Part 1. Get the connect.php from the php folder in Part 1. I have also included it in the Part 2 Source zip download.

That’s all we need from Part 1. Now let’s create the actionscript code.


Step 8: Create Object Settings – Register Button

First we need to give the register button a rollover cursor. We do this by using the buttonMode property.

register_button.buttonMode = true;

That is all we need to do to format our register button.


Step 9: Setting up The Register Button

We now need our register button to run a function that validates the input of a user. We can do this by adding an event listener and triggering the function when the user presses the button.

/*
when register button is pressed then the checkForm function runs.
*/

register_button.addEventListener(MouseEvent.MOUSE_DOWN, checkForm);

Step 10: Validate the Form

Before the user can submit the form they have to fill in all the fields. Remember to import the flash.events.* classes into your AS file. Follow the comments…

public function checkForm (e:MouseEvent):void {

	/*
	If all of the fields have more than one character sendForm() inits. 
	If not then the result_text will tell them to fill them all in.
	*/

	if (username_text.text != "" && password_text.text != "" && userbio_text.text != "") {
			
		sendForm();
			
   	} else {
			
		result_text.text = "PLEASE FILL IN ALL FIELDS";
			
	}
		
}

Step 10: Set up the URLVariables Class

Remember to import the flash.net.* classes into your AS file. The URLVariables class is used to store data in that you would send off to a external source at a later date.

We need to create a variable to hold this data in:

var phpVars:URLVariables = new URLVariables();

We use instance variables to store data:

phpVars.username = username_text.text;
phpVars.password = password_text.text;
phpVars.userbio = userbio_text.text;

Step 11: Set up the URLRequest Class

Next we need to make a URL request to get the location of our php file. This URLRequest is also what we pass our php variables through. When we load this request the php variables are sent to the php file.

var urlRequest:URLRequest = new URLRequest("php/register.php");

/*
the POST method is used here so we can use php's $_POST function in order to receive our php variables.
*/

urlRequest.method = URLRequestMethod.POST;

/*
this attaches our php variables to the url request
*/

urlRequest.data = phpVars;	

Step 12: Set up the URLLoader Class

The URLLoader Class allows you send & receive data from external sources. In this case we will be sending our URLVariables data to the php file via our URLRequest. Follow the comments…

/*
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);

Step 13: Create the showResult() Function

In the sendForm() function we added a listener to run the showResult() function when the php file had been executed. Now let’s create it…

/*
function to show result
*/
		
public function showResult (e:Event):void {

	// e.target.data is referring to the php file's output. We define result_message in the php file later on.
		
	result_text.text = "" + e.target.data.result_message;
		
}


Step 14: Create the PHP File

Create a new php file, name it register.php and save it in a new folder called php.


Step 15: Flash to PHP Communication

In order to continue we need to be sure whether our php and Flash files are talking to each other. Open your text editor of choice and open the register.php you just created. Again, follow the comments…


<?php 

/*
use connect.php to connect out database
*/

include_once("connect.php");

/*
create the test POST VAR - $_POST['username'] is used to phpVars.username from the phpVars variable we set.
*/

$username = $_POST['username'];

/*
print the output - This is sent back to flash. As you can see result_message has now been defined.
*/

print "result_message=$username";

?>

Now upload the files to your server for testing and check it out. If the resultant text is now the same as the username you have successful communication between Flash and php. Now delete the contents of register.php.


Step 16: Include Connection File

Now we have successful connection we can connect to our database from Part 1. We do this by including our connect.php file we made in Part 1.


<?php 

include "connect.php";

?>

Step 17: Create POST Vars

We need to create POST vars to receive the php vars we sent and defined as POST variables.

/*
create POST vars to receive data from flash
*/

$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
<?php 

/*
connect to database
*/

include "connect.php";

/*
create POST vars to receive data from flash
*/

$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];

?>

Step 18: Create the SQL Statement

Let’s now create the SQL statement that will add our values and store them in a new record in the database. Follow the comments..


/*
INSERT INTO users - This means we want to insert a record into the users table.

(username, password, user_bio) - We then specify the fields we want to add our data to.

VALUES ('$username', '$password', '$userbio') - We then specify which data we want in each field.

*/

$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";

Step 19: Back to Flash


/*
Next we send off the query to communicate with the database. To send the result_message back to flash we use the exit function. 
*/

mysql_query($sql) or exit("result_message=Error");

exit("result_message=Success");	

Step 20: Completed PHP Script


<?php 

/*
use connect.php to connect out database
*/

include_once("connect.php");

/*
create POST vars to receive data from flash
*/

$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];

/*
create the mysql query
*/

$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";

mysql_query($sql) or exit("result_message=Error");

exit("result_message=Success");				  

?>


Step 21: Completed ActionScript File

package {
	
	import flash.display.*; 
	import flash.events.*;
	import flash.net.*;
	
	public class register extends MovieClip {
	
		public function register ():void {
			
			/*
			First we need to give the register button a rollover cursor. We do this by using the buttonMode property.
			*/
		
			register_button.buttonMode = true;
			
			/*
			give the register button a mouse event
			*/
			
			register_button.addEventListener(MouseEvent.MOUSE_DOWN, checkForm);
			
			/*
			set all the fields to no characters
			*/
			
			username_text.text = "";
			password_text.text = "";
			userbio_text.text = "";
		
		}
		
		/*
		validate the user's input
		*/
		
		public function checkForm (e:MouseEvent):void {
		
			if (username_text.text != "" && password_text.text != "" && userbio_text.text != "") {
			
				sendForm();
			
			} else {
			
				result_text.text = "PLEASE FILL IN ALL FIELDS";
			
			}
		
		}
		
		/*
		function we use to send the form
		*/
		
		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.password = password_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("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;
		
		}
	
	}

}

Conclusion

Now you can go to the demo, register, then go to the login page and try it out. Thanks for reading this two-part series!


Other parts in this series:«Create a Flash Login System Using PHP and MySQL – Part 1

George Baker is thePhoenix on Activeden
  • http://burntfeathers.com George Baker
    Author

    To login after registering click here.

  • Maxwell Lee

    Hello George!, This Is another Wonderful Tut by You, However i was wondering, would it be possible to make it in such a way so on the log-in screen, There is a register button, which will take you to the register option? I’m Kind Of confused on how to do so,

    Also Thanks for The Tut!

    • http://burntfeathers.com George Baker
      Author

      Thanks :)

      You can simply place a button in the login form.

      give it instance name of reg_button

      reg_button.addEventListener( MouseEvent.MOUSE_UP, navi);
      
      function navi (e:MouseEvent):void {
      
      navigateToURL(new URLRequest("http://yourloginsite.com&quot;), "_self")
      
      }
      • Maxwell Lee

        Hey, thanks it works George,
        Once again Nice Tut!

  • Ben R.

    Thanks for the tutorial.

    I saw this post on theFlashBlog and thought it was relevant.

  • http://123.456 Palim Palim
  • http://www.riverflowing.com Mike

    Yes, I was remembering that post mentioned by Ben when I saw this tutorial. I also recommend you take a look at PHP 5 for Flash for a good tutorial on login authentication with sessions. Even though the book is many years ago, I think it has a good take on security and designing a login system I still use through Flash, PHP, and mySQL.

    Ideally, I think should have the login screen in a separate Flash file than the main Flash content.

  • http://www.thehellrider.com hellrider

    thanks it’s great

    • http://burntfeathers.com George Baker
      Author

      Thanks :)

  • http://www.photoshopfriends.com/ Photoshop Friends

    great tutorial… i bookmarked it for a project i have in the making!

    • http://burntfeathers.com George Baker
      Author

      Thanks :) Look into md5 for security.

  • Jordon

    How safe of a login system would this be? Would it be easy to obtain other users login information? I am not really to good with data bases, PHP, or mysql.

    • http://burntfeathers.com George Baker
      Author

      I forgot to add security which I apologize for now. Here are some things you could look into to make your login more secure.

      1. md5
      2. mysql_real_escape_string
      3. stripslashes
      4. stripcslashes

      Thanks :)

  • Sagar

    Hi George,

    Awesome tut. again!

    Just a suggestion can you make a part 3 to
    make your login more secure.
    1. md5
    2. mysql_real_escape_string
    3. stripslashes
    4. stripcslashes

    Thanks again!
    Sagar

  • http://spiegelberg.dk Spiegelberg

    Hey George.
    will it be possible to go a new url if my username and password is correct?

    i tried with:
    <pre name="code" class="php">if ($login_counter > 0) {

    $URL='http://www.xxx.com&#039;;

    header ('Location: '.$URL);

    }
    else ….

    but without any luck.

  • mark Chynoweth

    Great tutorial! I really appreciate it, and it works well. I’m experiencing one small snag, however. The output message, that is result_message come up as “undefined”. I have looked thoroughly for the reason for this but have come up empty. This occurs at both registration and login so I assume it has something to do with mysql query, or the way that it is processing the results. Any feedback on how to handle this? Thanks in advance.

    • http://tableseven.org Tom

      Regarding the ‘undefined’ problem, ensure you’re testing from within the browser (localhost) and not within Flash after publishing. (e.g. http://localhost/project/main.swf)

  • carlito

    hello, i need some help i am new with php and mysql i neet to make a login system with flash as2.that will be name, surename, e mail, invoicing, adress, phone, company with this fields new visitor will register to flash site if already registered just username and password requried so how can i do this with flash as2

    sorry for my bad english:)

    best regards

  • Vasa

    Hello everybody! Thanks for the lesson, very good!
    If you have problem with “undefined” in result_text:
    Copy from source folder “php” to your “localhost/site_name” and in the class Main.as replace:
    var urlRequest: URLRequest = new URLRequest (” lotsalhost / site_name / php /controlpanel.php”)
    Sorry for English )) i am from Russia ;)

    • Vacsa

      oops…
      var urlRequest: URLRequest = new URLRequest (” localhost / site_name / php /controlpanel.php”)

  • pippo27

    result_text “undefined”.

  • yi xian

    hi, i would like to ask is there any way to make it display the current logged on username on the welcome page?
    for example like when i successfully login to the system, then it should navigate to the welcome page, i want it to display the username on top corner, something like” welcome! XXX.”

  • http://www.wakeupstyle.com.ar nico

    I have the solution to the UNDEFINED issue.
    The file “connect.php” have an “echo” with the “success” text… well, you only have to comment (//) this line or delete it to solve the problem :D

    • Ragu

      Nice Tutorial …Thx

  • Chi

    Great tut. thanks so much. I am encountering one issue when i publish and run locally. I get a message that says “Fonts should be embedded for any text that may be edited at runtime, other than text with the “Use Device Fonts” setting. Use the Text > Font Embedding command to embed fonts.”

    The certain letters do not type in the registration fields, while others do type. however, when i run from server through the browser, the same swf file works fine. just locally its not working.

    any hints?

    thanks, chi

  • Chi

    I figured it out. If you have CS5, you may need to embed the fonts in the 3 fields. click on the “embed” button in the character section of properties.
    chi

  • Jarrod Holder

    Asked this in Part 1 comments as well, but thought I might get different users to respond on this one…

    Anyway to get this working outside a browser? I am creating a game that has to run on the desktop as a Mac Projector App (dont ask why…it is incredibly convoluted) and need to be able to connect to the DB on the server. Any help would be awesome.
    Thanks!

  • Jennifer

    This might sound silly, but I’ve made a simple game and it needs these scripts, but I’m unsure of where in my actionscript I should put in calls to this code or if I can simply add it in to the code I’ve got. I’m self-taught in actionscript 3.0, so I’m sort of stumbling through things.
    How would I go about attaching this to the game so players have to register/log in before playing?
    Good tutorial, by the way, I just need a little help in that area. Perhaps a suggestion of making a similar tutorial for games would help those like me – I notice I’m not the only one asking questions regarding games.

  • Adam

    I seem to be getting ‘undefined’ as well when I use this code. Then whn I changed the path in the main.as file to ‘../php/controlpanel.php’ I’m not getting anything at all except an error in Safari that reads:
    http://www.servername.com/crossdomain.xml Not found.

    Sounds like a permissions issue….any ideas how to solve this?

    • Adam

      Well I created the crossdomain.xml file but still getting ‘undefined’…no idea why…very frustrating.

  • Jordan

    Thanks George, love the tutorial! However, I second (or third, actually) the call for applying this to a desktop-based game. It’d be great to see a working example of that.

  • george

    same prob! result text >>>> Undefined????!!!!
    help!!!

  • http://www.davidhill.tv David Hill

    This is a wonderful tutorial that I was able to successfully complete the first time. However, as with Part 1, I am unable to make it work with re-directing to a new URL … I would like the register page to re-direct to the log in page when completed and I would like the log in page to redirect to a different URL. I suspect it is rather straight-forward but I am not well versed with AS. If anyone can help I would be ever grateful. Keep up the good work.

  • KermEd

    In order to bypass the undefined error I changed the last line in the register.php to:

    print “systemResult=$username”;

    Fixed it for me

  • http://www.apialliance.com.au Ian Cox

    Great tutorial, after some self inflicted difficulties was able to adapt it for internal office secured network. Would love to see further tuts expanding on this one to Edit and Delete database records.

  • Peter

    Thanks so much for great tutorial :D