Taylor Swift
Taylor Swift

Reputation: 242

How to write to a text file in ActionScript 3.0?

I'm working on a method of authentication, and i have 2 text fields named 'username' and 'pass' I want to make it so that when the user enters their username and password, that info gets stored into a text file. So when they log back in, it reads the username and password from that text file to log in. How can I do this? Thanks :D

Upvotes: 3

Views: 5472

Answers (2)

Tirtha
Tirtha

Reputation: 872

ideally, you cannot write a file using flash(unless it is an AIR application).FLash is supposed to run on the browser, so allowing it to access the system resources(Like your file system) is a security threat. However, AIR is a technology where Flash runs as a desktop application, and in such condition, it can write a file.

Shared Object is a approach where flash can save some temporary data in browser environment, but, if you clear cache and delete browser files, i guess it'll get flushed as well.

Upvotes: 0

francis
francis

Reputation: 6359

Saving to a text file is possible (using the File class in AIR) but this is really not a great approach. Instead you should checkout the SharedObject class

Quick example:

 var sharedObject:SharedObject = SharedObject.getLocal("userInfo"); //this will look for a shared object with the id userInfo and create a new one if it doesn't exist

Once you have a handle on your sharedObject

sharedObject.data.userName = "Some username";
sharedObject.data.password= "Some password"; //it's really not a good idea to save a password like this
sharedObject.flush(); //saves everything out

Now to get your data back, elsewhere in the code

var sharedObject:SharedObject = SharedObject.getLocal("userInfo");
trace(sharedObject.data.userName);
trace(sharedObject.data.password);

This object is saved locally to the users computer. It's very similar to a browser cookie.

Now saving out a password to this object in plain text is not a good idea. A better plan would be to validate the login information on a server and store a session id of some kind in this object.

in pseudo code:

function validateLogin(){
    var sessionID = server->checkLogin(username, password); //returns a string if authed, nothing if not
    if(sessionID){
         sharedObject->sessionID = sessionID;
    } else {
        //bad login
    }
}

More reading:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html

http://www.republicofcode.com/tutorials/flash/as3sharedobject/

Upvotes: 5

Related Questions