Ultrashock Tutorials >Flash5 > Flash5 and Cookies  
 
By: Nik Khilnani, Nuthing.\


Source File

 
Flash5 and Cookies
 

 

If your reading this I take it you have built a Flash website a few times and feel there's something lacking. Something that gives your website a friendly feel to it and makes browsing it easier for the visitors that come to your website. You might want them to be able to customize certain features. Maybe be given the option to skip the site intro the next time they visit. Having to view or wait for a 300 Kb intro to load on every visit gets a bit irritating after a while. We know the intro is cool but... lets be realistic. For example I used the CGI script you will find in this tutorial's source zip file to create Ultrashock's skip intro feature.

Maybe you want more than just a skip intro option. You want to have the site remember the visitors name, his visit count, his choice of background color for the site or where he left a certain object(like menu/panel layout) on the stage. All of this can be done by integrating Flash with CGI/cookies. A better, tougher, more effective method is to give the visitors a user name and password and store the information on the server. A good example is WDDG's Flash Challenge. While this method uses the same concepts behind the data exchange between Flash and CGI there is a big difference in the CGI scripts. There is a lot more scripting involved and databases could be hard to understand in the beginning. Many users starting out with Flash do not have access to databases on their website, do not have the server space to store all this user information or just plain do not want to. They can still let the user customize the site by using CGI cookies. To help refresh 'cookies' are small files stores on a users computer that store information about a website. Today cookies are pretty safe but it would be a good idea not to store credit card information in cookies.

Before we move on you should know this tutorial has a few prerequisites. Yes, we're back in school. You need to be familiar with the following:

  • A bit of CGI /Perl programing like being able to use and create sub methods and being able to understand and manipulate code. A Perl programming book nearby would be helpful.
  • You need to know how to construct movie clips and be able to understand a Flash Fla. Since it is beyond the scope of this tutorials to start from Flash5 basics I need you to be familiar with Flash5 scripting.
  • Lastly you need to know how to read in information from a text file or script works. Basically how to use the Load Variables method in Flash. Jason Krogh's Flash4 Guestbook tutorial explains this well.

OK, So what's involved?

Well, first of all we need to decide which features we want customizable in the Flash movie. After doing that we need to decide how many variables we will need to store the customizing information, what names we will give them and what values they will hold under different scenarios such as during the visitors first visit and every subsequent visit. Once this is decided we can start designing the CGI script to make this baby work.

In our tutorial we will make the Flash movie remember the visitors name, his visit count, the color he/she chose for the site's background and the position of a draggable object. The reason I chose these features is that these cover the basic concepts behind the different implementations one might use to create a site that does what I mentioned and more, like allowing the visitor to customize and save the site's layout so he can have certain windows (or anything else) be exactly where he left them. These are the building blocks. You have to use them to build bigger, better and more useful sites.

To see a demo version of the tutorial in action click here

Lets get to work

The way I will construct the Flash movie is like so. Each customizable feature will be in its own movie clip. This helps organize the contents of the movie so we know where everything is and more importantly, makes each feature's movie clip independent. Allowing each feature movie clip to react according to the data returned by the cookie reading CGI script. There will be 4 different movie clips, namely Color, Drag, Counter and Name. The variables associated with each movie clips are _root.color ( to store the color value), _root.dragXPos & _root.dragYPos (to store the drag objects X and Y position), _root.counter (visitor count) and _root.name (user's name).

Lets start by discussing the basic layout of the Flash movie. The Movie will be divided into three sections. The first section loads the Flash movie and the variables from the "cookie.cgi" CGI script. The second section displays the site and the last section sends the customized feature's variables to the CGI script to save the info. We get to the last section only when the user clicks the save button.

Setting up the movie clips

As discussed above, our flash movie is divided into 3 sections. Namely the loading, Content and Save sections. First lets deal with the Loading section.

The Loading Section

The load section basically loads the cookie information from the CGI script. We will use a mode variable that tells the CGI script what we want to do, load information or save information. Therefore the 'load' variable can has two possible values, "load" and "save". Hence we set the mode variable to "load" and send it to the script in the Load Variables method call.

_root.mode = "load";
loadVariablesNum ("cookie.cgi", 0, "GET");

We make the Flash movie stall or loop until we confirm that the CGI script has sent the movie all the information to the Flash movie and the entire Flash movie has been loaded. We do this by checking for a variable I call "done" placed at the end of the list of variables sent by the Flash movie. The code is simple. If 'done' is equal to the predetermined value (1) and, the entire Flash movie has been loaded, we move on the next part of the movie , else we loop till all the information and Flash movie is loaded. This is done because different servers and different bandwidth cause the load time to be different every time the movie is loaded. Here's that code.

if ((done <> 1) or (this.getBytesLoaded() < this.getBytesTotal())) {
    gotoAndPlay (2);
}      
The Content Section

Now that we know exactly how the script works lets start the Content portion of the movie. The reason for looking at the script before finishing the Flash movie is so that we know what information the Flash movie will receive under the different circumstances and make our understanding clear.

As we discussed before there will be 4 different movie clips, namely Color, Drag, Counter and Name. The variables associated with each movie clips are '_root.color' (to store the color value), '_root.dragXPos' & '_root.dragYPos' (to store the drag objects X and Y position), '_root.counter' (visitor count) and '_root.name' (user's name).

The Color Movie Clip

Lets start with the Color movie clip instanciated as 'color'. One cool enhancement to Flash5 is the color object. Using the color object we can change/modify and retrieve the color properties of any movie clip. Since Actionscript is Object oriented in Flash5 we need to create an new color object. The color object constructor's design definition requires us to specify the target while creating the new object. Therefore I created a background movie clip in the root level with a flat filled color and give it an instance name 'bg'. I target the new color object to this movie.

MyColor = new Color( "_root.bg" );


I place this code in the load clip event of the 'color' movie clip. Now the way we set up the CGI, if the '_root.color' variable is empty, this is the users first visit. If not the user has been to the site before and may have saved a background color preference. Therefore if the '_root.color' variable is not empty we need to apply the saved color information to the color object we created.

if (_root.color <> 0) {
  MyColor.setRGB( _root.color );
}
Therefore our code in the load event of the color movie clip looks like this.
onClipEvent (load) {
  MyColor = new Color( "_root.bg" );
  if (_root.color <> 0) {
    MyColor.setRGB( _root.color );
  }
}

In the color movie clip we create a simple menu animation the opens and closes a menu on clicking a button. The menu in the movie is a group of buttons that will change the background color. On clicking any button we modify the RGB property of the MyColor object. Since we want to record this information so it can be stored in the cookie, we assign the desired color to the '_root.color' variable and then apply the contents of the '_root,color' variable to the MyColor object. The code is the same for all the buttons in this movie clip . The only difference lies in the hexadecimal value assigned to the '_root.color' variable.

on (release) {
    _root.color = 0x330000;
    MyColor.setRGB( _root.color );
}

The Drag Movie Clip

Now lets move on to the Drag movie clip instance simply named 'drag'. This movie clip is pretty simple. Its just a movie clip with some shape/graphic drawn in it. The number of frames do not matter since the Actionscript will be placed in the clip events' action area. Just as in the Color movie clip we check if the '_root.color' variable was empty and if it was not we executed code to apply the value stored in the '_root.color'. We do something similar in the load clip event, only in this case we check the '_root.dragXpos' and '_root.dragYpos' variables. If both are empty I assume this is the users first visit, since the probability of the user placing the dragged object at (0,0) is extremely unlikely. If either of the 2 variables contain code, the user has been to the page before and saved the drag objects position. Therefore we need to apply these values to the drag object as follows. Its that simple.

onClipEvent (load) {
    if ((_root.dragXPos <> 0) and (_root.dragYpos <> 0)) {
        this._y = _root.dragYPos;
        this._x = _root.dragXPos;
    }
}

In Flash we do not always need a button to check if the mouse is pressed over a movie clip. We can use the mouseDown and mouseUp clip events to find out the obvious and use the hitTest method to check if the mouse is pressed over the current movie clip as I have done in this case. This is a pretty simple method well documented in the Flash5 help files. I just copy-pasted the code from there, he he. On pressing the mouse we need to enable dragging of the current 'drag' movie clip and when the mouse is released we need to stop the dragging and store the current X and Y position of the drag movie clip. Here's what the code looks like.

onClipEvent (mouseDown) {
    // Start dragging is mouse over pressed down over this MC
    if (hitTest( _root._xmouse, _root._ymouse, false)) {
        startDrag ("", true);
    }
}
onClipEvent (mouseUp) {
    // Stop dragging and save the current X and Y positions
    stopDrag ();
    _root.dragXPos = this._x;
    _root.dragYPos = this._y;
}

The Counter Movie Clip

Now lets look at the counter movie clip. This is the simplest movie clip in the tutorial. It only contains a graphic and a dynamic text box to display the current '_root.counter' variable. You definitely do not need the code for that. If you do we have a big problem.

The Name Movie Clip

The last important clip is the name movie clip. By now you should be telling me how this movie clip is made. This clip has 2 frames with stop actions. The first frame allows the user to input his name into an input text box and the second only displays the value stored in the '_root.name' variable. This is because on the user's first visit we need to let him enter his name so that we can store it. Since during the first visit the CGI sets the '_root.name' variable to a default text we check if the variable is equal to this text and send the current frame of the movie to the specific frame in the movie. I use the default text "Enter Name". This serves to check if this is the users first visit also displays an instruction in the input text box, therefore serving a dual purpose. So this is what we have in the load clip event of the name movie clip. Here frame 1 contains the input text box and frame 2 contains the dynamic text box to display the value stored.

onClipEvent (load) {
    if (_root.name eq "Enter Name") {
        this.gotoAndStop(1);
    } else {
        this.gotoAndStop(2);
    }
}

Additionally the content sections contains a save button. On clicking the save button we are sent to the save section of the movie that sends the variables to the CGI script.

Lastly The Save Section

On clicking the save button we need to send the variables to the CGI script and have them saved to the cookie. Therefore we set the mode variable to 'save' and then use load variables feature to send the data. Then we use the same technique described in the Load section to make sure the CGI script saved the info.


              _root.mode = "save";
              loadVariablesNum ("http://nuthing.com/miko/cookie.cgi", 0, "GET");     

The nitty gritty CGI/Perl stuff !

Now that we built the Flash movie we know what information the CGI script should send and receive from the Flash movie. So now lets write the script.

We will use a mode variable that tells the script what we want to do, load information or save information. Therefore the 'load' variable can has two possible values, "load" and "save". In the CGI script we will first check for the mode variable. If it is equal to "load" we will execute code to return variable information to the Flash movie, else we need to take the information sent by the Flash movie and save it to the cookie. I use the parseForm method to find the value stored in the 'mode' variable. Hers what the outline looks like in Perl.

# Parse the form contents 
&parseForm;

# If the current mode form field is equal to load then we start the sequence 
# to  retrieve the cookie

    if($FORM{'mode'} eq "load") {

# Code to read the cookie & send the info to Flash in a palatable form.
	
     }

    if($FORM{'mode'} eq "save") {

# Code to take the information sent by Flash and save it goes here.
	
     }

If this is the users first visit we will have the script set a 'first visit cookie'. This cookie basically sets a cookie with the counter set to 0 and the other variables to a an empty string or null value. Doing this displays a value 0 for the counter variable and the other empty variables tell the Flash movie to display the default site preferences. After this we set the name variable to a default value throw it to the Flash movie. On every subsequent visit the script will increment the counter variable and resave the cookie. Then it will send the variable info saved in the cookie to the Flash movie. Here's what that code looks like.

# Parse the form contents 
&parseForm;

# If the current mode form field is load then we start the sequence to retrieve the 
# cookie

    if($FORM{'mode'} eq "load") {

# Call function to retrieve and break up the cookie information
	&getCookie;

# If the counter in the cookie is a null value this is the first visit
	if($counter eq "") {

# Set the first visit cookie that initializes the cookie with counter=0
	   &setFirstCookie;

# set the HTML header and print counter=0 to indicate first visit and initialize
# the name variable to default

	   &setHeader;
           print "counter=0&name=Enter+Name&done=1";

        } else {

# if the counter variable is not empty or null means the user has been to the site
# before and a cookie exists... so we increment the counter and set the next cookie.
# then we set the header and throw the information out.

	   $counter++;
	   &setNextCookie;
	   &setHeader;
     print "counter=$counter&name=$name&dragXPos=$X&dragYPos=$Y
&color=$color&done=1"; } }

On clicking the save button we need to send the variables to the CGI script and have them saved to the cookie. Therefore we set the mode variable to "save" and then use load variables to send the data. In the CGI script we check for the value of the mode variable. If it is equal to "save" we merely have the script save the variables to the cookie and return a confirmation like "done=1".

# if the mode  variable is save then we take the form info & save it to the cookie.
     if($FORM{'mode'} eq "save") {
          &setCookie;
          &setHeader;
          print "done=1";
    }

Well, what happens if someone just calls the script? Like some sneaky guy peaking at your flash code and found out the URL of the script you used. This is what I did.

# If the mode is not equal to load or save someone is trying to hack in... so we
# print a dummy message

    if(($FORM{'mode'} ne "load") && ($FORM{'mode'} ne "save")) {
	   &setHeader;
           print "What you trying?? huh??";
     }

(For more information on the sub methods used please refer to the script source by clicking here.)

Is that it?

Yes. As you can see it isn't very hard to use Flash with CGI. Its just knowing how to put the two together and how to organize and set up the movie clips. I think programming the CGI/Perl part is tougher than the Flash Actionscripting.

These basic building blocks show you how cookies and Flash work: how to save the background color, name, counter , position of a clip. Using these blocks you can create a really cool customizable interface. Just use your imagination.
 

 
©2001 Ultrashock.com Inc. - All rights reserved