In this article, Jesse will using both PHP 3.0 and Flash 5.0 to create a simple but effective "Dynamic Counter" swf file for your website.
Hey people, welcome to the Dynamic Counter tutorial. In this tutorial we will investigate how to create a hit counter for your flash page. OK let's get into it!
Before we start with flash we need to create a data-storage file. This is just a text file called 'counter.txt', which you can create with your favorite plain text editor. Note the some text editors might try and store your text in Rich Text format, which will cause you problems. I'm using Windows Notepad, which comes with all versions of Windows and can be accessed through Start > Programs > Accessories> Notepad).
Create your text document, and enter the following code:
count=0&loaded=1
Now save your document as counter.txt in the directory you plan to use for your Flash counter. Now, briefly, I will explain what you have just done and why. The purpose of this file is to store data for us to read and adapt for use in our counter count=0 - sets variable count to the value 0 (zero). & (ampersand symbol, Shift-7) - indicates the end of one variable and the beginning of another loaded=1 - sets the variable loaded to the value 1, I'll explain why later.
Now call up Flash 5 and create a new document (Ctrl-N). Save your file as "counter.fla" in the same directory as your counter.txt file. Now create a new Movie Clip Symbol (Ctrl-F8) and name it 'counter'. Leave it empty for the moment. Open up your Library (Ctrl-L) and drag one copy of your empty 'counter' clip onto the stage. Select that instance of your symbol and name it 'counter' using the instance panel (Ctrl-I).
Now right click the counter instance and select Edit, (or Ctrl-E).
Create 3 keyframes within the counter symbol stage, at frames 1, 2 and 3. Double click frame 1 to bring up the Actions panel for that frame. Now enter the following code:
if (startup eq "")
{
startup = "Run Already";
loadVariables ("counter.txt?" add random(2000), "/counter");
}
Note the best way to enter code is to just copy it from here and paste it (using Expert Mode) into your actions panel. This is one of the joys of Flash 5. To access Expert Mode use Ctrl-E or click the right-facing menu arrow atop the Actions window and select Expert Mode from the drop down menu.
Now, there's no use entering code if you don't know what it does! So let's take a look at the code above:
The first line is a conditional clause: this means it checks one thing before it does another. A good analogy is driving: you don't press the accelerator without starting the car, (or maybe you do, but you shouldn't), so you've got to check if the car's started first, before you press the accelerator. This conditional clause asks if our variable startup is equal to nothing ( "" indicates nothing).
Why do this?
Because we're going to loop back to this frame and I only want to carry out these operations once, not every time we come back. That's where the second line comes in: by setting our variable startup to any value other than nothing, we ensure that these instructions will be ignored every subsequent time we visit this frame.
The loadVariablesNum command is the important aspect here though. This command replaced the standard loadVariables command in Flash 4 and is used for loading variables into Flash from an external source, such as a text file on the server. These variables are loaded as expressions, (numbers), rather than strings. counter.txt is the name of our data-storage file, which we will deal more with later.
The remainder of the code, produces a random number, random (999999), and concatenates (attaches) it to the end of our file-name, after a question mark. This question mark, random number combination is effective against browser cache conflicts.
Now on to Frame 2. Double click your keyframe in frame 2 to open the Actions inspector for that frame. Now enter the following code:
if (loaded == "1")
{
gotoAndPlay(3);
}
else
{
gotoAndPlay(1);
}
What kind of statement is this?
If you said 'It's a conditional statement Jesse!' then give yourself a pat on the back. Yes, conditional statements are everywhere. This one is a bit more complex than the last though. First it checks our condition, in this case loaded == "1" or 'Does the variable loaded hold the string value "1"?'
This is where the extra variable in our text file comes in. Data files won't always load in the split-second between one Flash frame and another. In this case they probably will because the file in question is only a few bytes long, but it's good practice to add an additional variable at the end of your data file which you can use to check if the data file has completed loading.
If the data file has completed loading, Flash will go to and play, Frame 3. If, somehow, the file is not yet fully loaded, Flash will go to and play frame 1. This is the loop I mentioned earlier and the reason behind the conditional statement in the first frame. In the highly unlikely situation that the data file is not yet loaded, Flash will loop until it is.
Frame 3 is the last keyframe in our counter symbol. It is on this frame that we will display our counter value. To do this we use the text tool and the Text Panel to insert a Dynamic Text field. Name your field "count" and uncheck 'selectable' on the text panel. Set the font, color and size as you wish, and remember to depress the include numbers outline button on the Text Panel.
Now open up the Actions inspector for frame 3 and enter the following:
count = Number(count) + 1;
loadVariablesNum ("counter.php3?count=" + count, 0);
stop ();
Line one of this code converts count to a number from a string, and adds 1 to its value. We must first convert it to a number because loaded variables begin as strings, (a sequence of literal text), and you can't add a number to a string of text: 1 + "test" is invalid. Line two calls our PHP script, which we will talk about below, and tells it the new value of count.
Line three contains an arbitrary stop() command. Which stops this symbol from looping back to frame 1.
The Script
PHP is a hyper-text-pre-processor. Basically it allows you to incorporate aspects of logic and programming into previously static HTML in order to generate dynamic HTML pages. It runs on the server and returns plain HTML to the user, so it is compatible with all modern browsers. PHP is much like ASP, but free. More information is available at:
http://www.php.net
We're going to use PHP to rewrite our data file each time our counter is incremented. Open your plain text editor again and enter this code:
<?php
$fd = fopen("counter.txt", "w");
fwrite($fd, "count=$count&loaded=1");
fclose($fd);
?>
Now save your file as "counter.php3", (not counter.php3.txt! Make sure you save it with only the .php3 extension).
Let's analyze this code.
Line one tells the server we're talking in PHP code. Line two opens our data file, counter.txt. Line three writes our new variables, sent by Flash, over our old data file. $count inserts the variable count which was passed by Flash, and &loaded=1 adds our extra test variable, loaded. Line four saves and closes counter.txt. Line five tells the server we're no longer talking in PHP code.
Now you need to upload all your files, except for your Flash source file (counter.fla) to your PHP compatible web-server and set their permission appropriately: counter.php3 must have read, write and execute access for this counter to work correctly. You can change access levels using the CHMod command. Contact your web host for further details about how to use CHMod.
Note also that you can't run this counter on you local machine to test it, unless you are running a web-server program such as Microsoft Personal Web Server. If you try to open the file in your browser, nothing will happen. This is for two main reasons. Firstly, you cannot use the no-cache string we used in keyframe one without running a web server locally. Secondly PHP will only run on computers with the proper modules installed: if you wish to run PHP at home, grab a copy from www.php.net for free.
Now on your server, Chmod the php file to 665 (-rw-rw-r-x) and the text file to 666 (-rw-rw-rw-) and run it.
That's it! You should have a working counter which increments each time you get a hit on your flash file.
If you don't check all your code, then consider these other possibilities:
Most hosts support the .php3 extension for PHP but some may be strict and require another extension (such as .php). If this is the case your script will not execute because it is not recognized by the serve as server-code. You must rename your script .php (or whatever is appropriate, check your server documentation) and also change all references to .php3 in the Actionscript to .php (or whatever is appropriate).
Have you set your permissions correctly? The directory in which counter.php and counter.txt reside on your server must have the appropriate access permission at the client level. If you are using FTP or Telent to upload your files you can type:
chmod counter.txt 666
chmod counter.php3 665
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More Flash Articles
More By Jesse Stratford
developerWorks - FREE Tools! |
Learn how you can extend modern application lifecycle management to IBM System z through the IBM Rational Software Delivery Platform (SDP). The Did you say mainframe? e-kit includes podcasts, webcasts, tutorials, white and red papers, demos, and articles designed to help ease the challenges of modernizing your enterprise. This complimentary kit for mainframe developers is a practical, how-to guide for making the most of an existing development environment, including the skills and infrastructure already in place at an established enterprise. FREE! Go There Now!
|
|
|
|
WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities. FREE! Go There Now!
|
|
|
|
Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase. FREE! Go There Now!
|
|
|
|
Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started. FREE! Go There Now!
|
|
|
|
Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months. FREE! Go There Now!
|
|
|
|
Get a free trial download of the latest version of IBM Rational Performance Tester V7.0.1, a load and performance testing solution for teams concerned about the scalability of their Web-based applications. Combining multiple ease-of-use features with granular detail, Rational Performance Tester simplifies the test-creation, load-generation and data-collection processes that help teams ensure the ability of their applications to accommodate required user loads. FREE! Go There Now!
|
|
|
|
Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, where he will overview Rational’s new offerings and programs to help customers accelerate software innovation on System z. He will discuss how these solutions help organizations extend their core business processes toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time. FREE! Go There Now!
|
|
|
|
Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise. FREE! Go There Now!
|
|
|
|
With IBM Rational Systems Development Solution, you can deliver products faster with higher quality. Within this kit, Read the “Model Driven Systems Development” white paper to see how to improve product quality and communication. Then check out the rest of the e-Kit to learn more about important topics that can affect the success of any software project through customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems. From start to finish, at every stage in your projects, Rational Systems Development Solution can help your company reach its full potential. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |