Flash
  Home arrow Flash arrow Dynamic Counter (PHP3+Flash 5)
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  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
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: 4 stars4 stars4 stars4 stars4 stars / 30
    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


    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! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Best Practices in Integrated Requirements Management

    Poor Requirements Management capabilities in an Enterprise have been linked to excessive project failures, escalating IT costs, and failure to deliver competitive advantage into the marketplace. Join Brianna M Smith from IBM Rational and learn about how successful organizations align IT and Business stakeholders through collaborative processes and tools for effective requirements management, and how an integrated approach across the IT lifecycle can provide unparalleled visibility and traceability to ensure that project teams are delivering on the business vision by "doing the right things" and "doing things right."
    FREE! Go There Now!


    NEW! Develop Systems Software Assets with IBM Rational Asset Manager

    Join us for this on demand webcast to learn about developing complex systems more quickly and efficiently. We'll cover market drivers for developing, governing and reusing systems software assets and how you can develop system software assets with Rational Asset Manager.
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Evaluate Rational Business Developer V7.1

    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!


    NEW! Hacking 101

    Join us for this web seminar to learn how you can defend your web applications from attack. Learn about the 3 most common web application attacks, including how they occur and what can be done to prevent them. We’ll also discuss manual versus automated approaches for scanning and identifying web application vulnerabilities and how IBM Rational AppScan, an automated vulnerability scanner, can help you automate more of what you are doing manually today.
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Section 508 of the U.S. Rehabilitation Act: Web accessibility compliance

    Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs).
    FREE! Go There Now!


    NEW! Using Rational Business Developer to enhance your developer productivity

    Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components.
    FREE! Go There Now!


    NEW! Whitepaper: Delivering SOA solutions: service lifecycle management

    The unprecedented scope of a service-oriented architecture (SOA) initiative brings to the forefront a number of management and governance issues that were sidestepped in the past. The key to a successful SOA implementation is managing and governing activities throughout the entire SOA delivery lifecycle by ensuring that services conform to the needs of all of the business’s stakeholders. Learn how service lifecycle management allows the business to ensure that the process by which services are defined, created, tested, deployed, optimized and retired is manageable, repeatable and auditable.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    FLASH ARTICLES

    - Critical Flash Vulnerability Heats Up the Web
    - More on Nonpersistent Client-Side Remote Sha...
    - Nonpersistent Client-Side Remote Shared Obje...
    - Using the Decorator Pattern for a Real Web S...
    - Using Concrete Decorator Classes
    - Delving More Deeply into the Decorator Patte...
    - The Decorator Pattern in Action
    - A Simple Decorator Pattern Example
    - Decorator Pattern
    - Organizing Frames and Layers for Flash Anima...
    - Organizing Frames and Layers
    - Using XML and ActionScript with Flex Applica...
    - Interfaces and Events with ActionScript and ...
    - Manipulating Data with ActionScript in Flex ...
    - ActionScript Syntax for Flex Applications







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek