SunQuest
 
       Flash
  Home arrow Flash arrow Dynamic Counter (PHP3+Flash 5)
IBM developerWorks
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
Moblin 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
FLASH

Dynamic Counter (PHP3+Flash 5)
By: Jesse Stratford
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 29
    2003-04-18

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    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

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! A Layered approach to delivering security-rich Web applications

    As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper.
    FREE! Go There Now!


    NEW! Accelerating Software Innovation on i on Power Systems

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! Application Development Tools for the Mainframe Developer

    You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Download DB2 9.5 for Linux, Unix, and Windows

    Download a free trial version of IBM DB2 9.5 for Linux, UNIX, and Windows. DB2 9 is the result of a five-year development project that transformed traditional (static) database technology into an interactive data server that merges the high performance and ease of use of DB2 with the self-describing benefits of XML.
    FREE! Go There Now!


    NEW! Harnessing the power of SQL and Java for high performance data access

    Join this webcast to see how IBM Data Studio Developer and pureQuery can take the pain out of Java data access. uApplications developed using both Java and SQL have become a common requirement. Database connectivity using Java Database Connectivity (JDBC) to create an application is a multi-step tedious process, and tooling that covers both SQL and Java has been unavailable, until now. IBM Data Studio introduces the pureQuery platform: a high-performance, Java data access platform focused on simplifying the tasks of developing, managing, and optimizing database applications and services.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 1: Create a continuous build and integration environment

    Learn how to implement a build management system that uses and extends your existing automation technologies. This tutorial shows, step-by-step, how to install and configure IBM Rational Build Forge to manage builds for Jakarta Tomcat from source code.
    FREE! Go There Now!


    NEW! Integrating XML into Your Enterprise Using Data Federation

    XML has become a common way of storing business data as flat files and many data server vendors including IBM have provided ways to store this data within relational database systems. Increasingly collections of XML files are accessed like databases using an xQuery and other XML standard mechanisms. Businesses find the need to combine the traditional tabular structured data with XML formatted data. In this webcast, you’ll learn about IBM’s WebSphere Federation Server technology, which provides users with the ability to integrate these two data formats.
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! Software Change and Configuration Management Solution Guidelines

    This whitepaper provides areas to consider when evaluating any software configuration management solution. It addresses how the IBM solutions (Rational ClearCase and Rational ClearQuest) meet the needs and requirements of both project leaders and developers to provide successful Software Change and Configuration Management.
    FREE! Go There Now!


    NEW! Whitepaper: Achieving consistency between business process models and operational guides

    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!



    All FREE IBM® developerWorks Tools!

    FLASH ARTICLES

    - Using XML and ActionScript with Flex Applica...
    - Interfaces and Events with ActionScript and ...
    - Manipulating Data with ActionScript in Flex ...
    - ActionScript Syntax for Flex Applications
    - ActionScript in Flex Applications
    - A Closer Look at Apollo`s File System API
    - Using the File System API
    - ActionScript 101
    - Flash Buttons
    - Advanced Flash Animation
    - Creating Your First Animated Movie with Flas...
    - Flash: Building Blocks
    - Building Preloaders
    - Fun Things to Do with Movie Clips in Flash MX
    - Referencing Movie Clips in Flash MX






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway