Advertisement
FastClick Ad Network
  

 

READING AND WRITING COOKIE
(Flash MX and newer)

 

Note: the term cookie in this tutorial refers to the regular browser's cookie.  It does not refer to the Flash's shared object (sometimes referred as Flash-cookie).  If you're interested in Flash cookie, you can also read the Introduction to Flash Shared Objects.  Flash Shared Object is good alternative to regular cookies as it's easier to use.

From this point onward, whenever the word cookie is referred on this page, it refers to the browser cookie.  The focus of this tutorial  will be on concepts.  The code samples contain very basic functionality; as they're for illustration purpose only; and are not intended to be robust.  I also recommend that you read an article about the security risk related to cross scripting on Macromedia and this other website.  

Intermediate Action Scripting knowledge is required to understand this tutorial.  
    


 
Advertisement
FastClick Ad Network
 

WRITING COOKIE

 
    
Flash does not support writing a browser cookie directly (as of MX 2004) , so you must "call" an external script to write the cookie.  

On this tutorial, I will write the external script examples in JavaScript, ASP, and PHP.  The focus here is how the overall things are done, we're not concerned about robustness and details of the implementation code.  

The Flash movie

This movie contains 2 variables in the _root level of the movieThe variables are named: cookieName and cookieValue.  Later, we will write the code that pass those variables from Flash to an external script to create a cookie.   

For demonstration purpose, you can set the values in the textboxes (letters only please) and use one of the button to set a cookie.  You can use the links below to delete and view the cookies when you're done.  The View Cookie link below can be used to view the cookie that was set.  The Clear Cookie link below allows you to clear the cookie that you have set.

Clear Cookie(s)  
View Cookie(s)

Using JavaScript
To set a cookie using JavaScript, the Flash movie must have access to the JavaScript code (i.e.: be able to execute the JavaScript code).  The JavaScript code could be on the same html page as the Flash movie, or it could be on a .js file if needed.  Below is my JavaScript code.  It is a function, called setCookie.  It takes a name and a value as parameters .  This function is very simple for clarity reason, and should not be used on real applications.  

<SCRIPT LANGUAGE="JavaScript">
<!--
function setCookie(name, value)
{
  document.cookie = name+"="+value;
}
//-->
</SCRIPT>

Remember that we want to pass these two variables from Flash: cookieName and cookieValue.  What we want to do here, is to pass the variable cookieName and cookieValue from the Flash movie to the JavaScript's setCookie function shown above.  The most common way to do this is to use FSCommand (read here).  Unfortunately, while Internet Explorer for the PC supports FSCommand, some browsers do not.  To be compatible with most browsers, we should use an alternate way.  That alternate way is using the getURL function.  Although you normally use getURL to open another URL (web page), you can also use it to execute JavaScript code.   Simply type getURL("javascript:code");  where code could be a function call or actual JavaScript code.  (There is a security risk of using getURL in this way.  You should read about what and what not to do on Macromedia and this other website.)

Below, I use getURL to call the setCookie function.  Just calling the function is not enough, I also need to pass the cookieName and cookieValue.  To do that, they're passed as parameters.  

  // make sure the variables are valid
  if (_root.cookieName.length>=1 && _root.cookieValue.length>=1)
    getURL("javascript:setCookie('"+_root.cookieName+"','"+_root.cookieValue+"')");

Notice that I need to use single quotes around the parameters so that JavaScript will interpret them as strings.  So for example, if cookieName is set to: id, and cookieValue is set to: Permadi, the line becomes:

getURL("javascript:setCookie('id', 'Permadi')");

The above command causes the following code javascript:setCookie('id', 'Permadi') to be executed.  In turn, setCookie creates a cookie named id, with the value of Permadi.

Using ASP
Let's see how to do the same thing with ASP.  

Here's a sample ASP code.  It assumes that variables are passed on the standard input (ie: form).  That means that we need to use POST method.  This ASP file is named  setCookie.asp and is located at the same folder as the Flash file.  This code uses a standard ASP way to set a cookie.  If you don't know ASP, you should consult an ASP reference on the Response.Cookie object.

<%
Response.Cookies(Request.Form("cookieName"))=Request.Form("cookieValue")
Response.Write "done"    
%>

What we want to do here, is to pass the variable cookieName and cookieValue from the Flash movie to the ASP code.  To do that, the Flash movie can use several techniques.  They are: loadVariables,  the LoadVars object, or getURL.   I do not recommend using getURL here because it's generally not intended to send variables.   Let's see how it is done using loadVariables and LoadVars.  First, let's use loadVariables.  Here's an example of how to execute the ASP code using loadVariables:

if (_root.cookieName.length>=1 && _root.cookieValue.length>=1)
  _root.loadVariables("setCookie.asp?var="+Math.floor(Math.random()*1000000),"POST");

When Flash executes the loadVariables; the variables on the timeline of the sender movie.  The sender movie it _root in the above example.   Remember that in my example, _root has two variables: cookieName and cookieValue.  Those variables will be passed to the ASP. 

Notice that we use "POST" as the last parameter for the loadVariables.  When using POST, the variables will be accessible in the ASP as Request.Form("variableName").  To put it another way: we can access the variable cookieName and cookieValue with: Request.Form("cookieName") and Request.Form("cookieValue") respectively.  Note that "cookieName" and "cookieValue" in the ASP code matches the variable names in Flash.  This is how you map the variables between Flash and external scripts.   

(You can use GET, instead of POST.  If you use GET,  you'll need to replace Request.Form with Request.QueryString in the ASP.  Note that there is a limit of the number of characters if you use GET.) 

Notice that I added a random number after the asp filename to make sure that the request isn't cached (see what the issue is with caching here).  This is normally not needed unless you're changing the ASP file often.  

One more thing worth mentioning here is that loadVariables will send all of the variables belonging to the sender movie clip (the sender movie clip in my example is: _root).  If you have a lot of unnecessary variables, they will be sent also.  That is not good and can slow down the data transfer.  In my example, there are only two variables in the sender movie clip (_root), so it is acceptable.  If your movie clip does have a lot of variables, you should use the LoadVars object instead.  

With LoadVars, you can specify what variables to send (you can do the same with loadVariables, but you'll need to create a temporary movie clip and assign the wanted variables to it, then use that movie clip as a sender on loadVariables).  Below is an example of using LoadVars (assume I have a created the LoadVars object in _root named loadVarObject).  

if (_root.cookieName.length>=1 && _root.cookieValue.length>=1)
{
  lv=_root.loadVarObject;	 
  lv.cookieName=_root.cookieName;
  lv.cookieValue=_root.cookieValue;
  lv.sendAndLoad("setCookie.asp", lv, "POST");
}

Going back to the ASP code, I should mention that the last line, which is: Response.Write "done" is added to send a dummy data so that the  Flash movie can check when the script has finished executing.  

Note: To test the function, you need to make sure that the ASP file (setCookie.asp in my example) is accessible from the server (or, you might want to use URL instead of relative path).  Notice that unlike the first example, I omitted the random number, but you should include it if the ASP file changes often.  

Using PHP (4 and above)
Here's a sample PHP code.  It takes cookieName and cookieValue and then creates a cookie based on those values.  This file is named  setCookie.php  and is located at the same folder as the Flash file.

<?php
if (isset($cookieName) AND isset($cookieValue))
{
  Header("Set-cookie: $cookieName=$cookieValue");
}
echo("done");
?>

What we want to do here, is to pass the variable cookieName and cookieValue from the Flash movie to the PHP code.  The nice thing about using PHP is that you do not need to care whether Flash uses GET or POST.  You will have access to the Flash variables just by specifying the variable name, prefixed by a $ sign.  So, in the code above, $cookieName corresponds to the Flash variable cookieName.  

In the Flash side, the code is very similar to the code on the ASP section.  For explanation of what they do, refer to the ASP section above.  

if (_root.cookieName.length>=1 && _root.cookieValue.length>=1)
  _root.loadVariables("setCookie.php?var="+Math.floor(Math.random()*1000000),"POST");

Or, alternatively: 

if (_root.cookieName.length>=1 && _root.cookieValue.length>=1)
{
  lv=_root.loadVarObject;	 
  lv.cookieName=_root.cookieName;
  lv.cookieValue=_root.cookieValue;
  lv.sendAndLoad("setCookie.php", lv, "POST");
}

  


 
 

READING COOKIE

 
    
This section follows the previous section (Writing Cookie).  
Please read the previous section if you haven't already; it contains information that will help better understand the concept and pitfalls behind this method.  

Flash does not support support reading cookie directly (as of MX 2004) , so you must "call" an external script to read the cookie data.  Since JavaScript is the most popular scripting language at this point, I will write an example using JavaScript.  The next example will be using ASP then PHP.

The Flash movie

This movie is a modified version of the first movie on the top of this page.  It contains 2 variables in the _root.  They are: cookieName and cookieValue.  For demonstration purpose, you can type the cookie name, and then click one of the button to get it's value.  Assuming you have set the values previously, the value should be displayed.  Now let's see how the code works. 

Using JavaScript
Before we start, I should mention that using JavaScript in this situation is probably the least reliable way of doing this.  This is because not all browsers support JavaScript to Flash communications. 

From within the web page that contains the Flash movie, you must have a function that reads the cookie.  Here's mine, called myGetCookie.  It takes a name parameter which is the cookie name, and returns the value of the named cookie.  The Flash movie will need to send the name parameter to JavaScript.  We will see how this is done later.  Let's see the JavaScript side first.  Note that this function is very simple and should not be used on a real application.  

<SCRIPT LANGUAGE="JavaScript">
<!--
function myGetCookie(name)
{
  if (document.cookie)
  {
    var cookies=document.cookie.split(";");
    for (var i=0; i<cookies.length; i++)
    {
      var varName=(cookies[i].split("=")[0]);
      var varValue=(cookies[i].split("=")[1]);

      while (varName.charAt(0)==" ")
        varName=varName.substr(1,varName.length);

      // the escape() function will url encode the value				
      if (varName==name)
        return escape(varValue);
    }
  }
  return " ";
}
//-->
</SCRIPT>

To execute that JavaScript code, we unfortunately cannot use getURL as before because JavaScript can't  send back a data stream to the Flash movie.  So in this case, we need to use FSCommand (read more about it here).  

The requirement for FSCommand is that you must call a stub function, which is always named yourMovieName_DoFsCommand.  You can ask Flash to create most of tedious work for you, including creating that stub function.  To do that, go to the File>Publish Setting and select Template: Flash with FSCommand.  

Assume that I saved my movie as getCookie.fla, and that I selected default names in the Format tab.  After doing Publish, when opening the html page generated by Flash, there will be something like below (ignore the code in bold for now).  You can see that the Publish command has created a stub function called getCookie_DoFSCommand.  Notice that getCookie matches the ID and NAME of the Flash movie.

<SCRIPT LANGUAGE=JavaScript>
<!--
var InternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
// Handle all the the FSCommand messages in a Flash movie
function getCookie_DoFSCommand(command, args) {
  var getCookieObj = InternetExplorer ? getCookie : document.getCookie ;

  // Place your code here...
  if (command=="getCookie")
  {
        // myGetCookie function is defined above
  	var cookieValue=myGetCookie(args);
  	if (cookieValue==" ")
        {
  	  alert("Cookie not found, please set cookie first");
          cookieValue="[not found]";
        }
	getCookieObj.SetVariable("_root.cookieValue", cookieValue);
  }
}
// Hook for Internet Explorer 
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && 
  navigator.userAgent.indexOf("Windows") != -1 && 
  navigator.userAgent.indexOf("Windows 3.1") == -1) 
{
  document.write('<SCRIPT LANGUAGE=VBScript\> \n');
  document.write('on error resume next \n');
  document.write('Sub getCookie_FSCommand(ByVal command, ByVal args)\n');
  document.write('  call getCookie_DoFSCommand(command, args)\n');
  document.write('end sub\n');
  document.write('</SCRIPT\> \n');
}
//-->
</SCRIPT>
<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
 codebase="[edited]"
 ID="getCookie" WIDTH="450" HEIGHT="100" ALIGN="CENTER">
 <PARAM NAME=movie VALUE="getCookie.swf"> 
 <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#0099FF> 
  <EMBED src="getCookie.swf" quality=high bgcolor=#0099FF 
  WIDTH="450" HEIGHT="100" swLiveConnect=true 
  ID="getCookie" NAME="getCookie" ALIGN="CENTER"
  TYPE="application/x-shockwave-flash" 
  PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>
</OBJECT>

To enable Flash to call myGetCookie function, I added the code in bold.  The cookieName variable from Flash will need to be passed in the args parameter.  The value returned by myGetCookie is the cookie value (or blank if the cookie is not found).  We return this value to Flash in the:  getCookieObj.SetVariable("_root.cookieValue", cookieValue).  This command might seem unfamiliar, it uses one of the Flash built in object access method, which you can read more about here 

The Flash code that calls that getCookie_DoFSCommand function is shown below:

fscommand("getCookie", _root.cookieName);

It is quite straightforward.  The above Flash code causes getCookie_DoFSCommand to be executed.  In getCookie_DoFSCommand,  I check whether the command parameter is "getCookie" (note: since the only command we do is getting the cookie, it's not actually necessary to do this check).  It then executes the JavaScript myGetCookie function.  The returned value is then passed to Flash _root.cookieValue by using ActiveX in the line
getCookieObj.SetVariable("_root.cookieValue", cookieValue);
.

Using ASP
Here's a sample ASP code.  It takes cookieName from the standard input (ie: form), then returns the cookie value.  This file is named  getCookie.asp.

<%
  Response.Write 
    "cookieValue="&Server.URLEncode(Request.Cookies(Request.Form("cookieName")))
%>

The Server.URLEncode() function will URL encode the string.

On the Flash side, I am using loadVariables in this example:

root.loadVariables("getCookie.asp?var="+Math.floor(Math.random()*1000000),"POST");

Make sure that you read the Writing Cookie section above to understand this code.  Note: To test the function, you need to make sure that getCookie.asp is accessible by the Flash movie (remember that the ASP code needs to reside on a running server to be able to run.)  You might want to use URL instead of relative path).  

Notice that I added a random number after the asp filename to make sure that the request isn't cached (see here).  This is a good idea here since we don't know how often the cookie has changed.   You can also use GET, instead of POST; in that case, in the ASP file, replace Request.Form with Request.QueryString.  I recommend using POST because GET has a limited space (ie: if your movie has a lot of variables, the cookie name variable might not get sent).  On that note, if you have a lot of variables in _root, the code above is not a good idea. because that will cause extraneous variables to be sent (the loadVariables causes all the variables in the movie clip to be sent).  To avoid that, use LoadVars object (or create a temporary movie clip).  

Below is an example of using LoadVars (assume I have done a _root.loadVarObject=new LoadVars() elsewhere).  The benefit of LoadVars is that you can specify what variables get sent (you can do the same with loadVariables, but you'll need to create a temporary movie and assign the variables to that temporary movie clip, then use loadVariables on that movie clip):

lv=_root.loadVarObject;	 
lv.cookieName=_root.cookieName;                 // assign variables that you want to
                                                // be sent to the script
lv.randomizer=Math.floor(Math.random()*10000);  // prevent caching
lv.sendAndLoad("getCookie.asp", lv, "POST");     

The sendAndLoad causes all the variables within the calling object (loadVarObject) to be sent along with the request.  In this case, only cookieName and randomizer will be sent, since those are the only variables I added to the object.    

The response from getCookie.asp will be retrieved by the retriever object, which is the second parameter of sendAndLoad.  In this case, I use the same object (lv), and I can assign the returned value to the correct place (_root.cookieValue) by overriding the onLoad event handler.  

loadVarObject.onLoad = function(success) 
{
  if (success)
  {
    _root.cookieValue=this.cookieValue;
  }
}

 

Using PHP (4 and above)
Here's a sample PHP code (note that this example is for PHP 4 or newer).  It takes a variable named cookieName (which will be passed by Flash via Query String or STDIN), then returns the cookie value.  This PHP file is named  getCookie.php.

<?php
  eval("\$cookieValue=\$$cookieName;");
  $urlEncodedCookieValue=urlencode($cookieValue);
  echo("cookieValue=$urlEncodedCookieValue");
?>

Note: You'll need to write the php script differently if you're not using PHP 4 and above.  You can see what eval() does here.  It basically sets a variable named $cookieValue with the value of the variable $cookieName.  It then returns the string as cookieValue.  The urlencode() function returns the URL encoded version of cookie value.

Below is the code for the the Flash side.  

_root.loadVariables("getCookie.php?var="+Math.floor(Math.random()*1000000),"POST");

Or, alternatively:

  lv=_root.loadVarObject;	 
  lv.cookieName=_root.cookieName;                // assign variables that you want to
                                                 // be sent to the script
  lv.randomizer=Math.floor(Math.random()*10000); // prevent caching
  lv.sendAndLoad("getCookie.php", _root, "POST");// send back data to root
  
The code is very similar to the ASP way, and you can read about what the code does in the ASP section above.
  

permadi@permadi.com
 
(C) F. Permadi

<<INDEX>>

Terms of Use

 


 

 
Google