>
How To Create Your Own Stats Program (JavaScript,...
Welcome, Guest

by Himu on Thursday, 25 June 2009
How To Create Your Own Stats Program (JavaScript, AJAX, PHP)


Webmasters use certain programs, such as Google Analytics or Awstats, to complete this job for them. These programs obtain a wide variety of information about visitors to a site. They find page views, visits, unique visitors, browsers, IP addresses, and much

 

When creating a website, one main goal is to attract visitors. Traffic generation is a necessity for monetary purposes, showing off your work, or just expressing your thoughts. There are many ways to create traffic for your website. Search engines, social bookmarking, and word of mouth are just a few examples. But how do you know whether this traffic is genuine? How do you know if your visitors are coming back for a second time?

 


Web Statistics

These questions have raised the concept of web statistics. Often times, webmasters use certain programs, such as Google Analytics or Awstats, to complete this job for them. These programs obtain a wide variety of information about visitors to a site. They find page views, visits, unique visitors, browsers, IP addresses, and much more. But how exactly is this accomplished? Follow along as we present a tutorial on how to create your own web statistics program using PHP, JavaScript, AJAX, and SQLite.

View Demo of your Own Stats Program

To begin, let’s start with some simple HTML markup that will act as the page we are tracking:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
  5. <title>Web Statistics</title>  
  6. </head>  
  7. <body>  
  8.   
  9. <h2 id="complete"></h2>  
  10.   
  11. </body>  
  12. </html>  

The h2#complete element will be filled dynamically with JavaScript once the page view has successfully been tracked by our web statistics. To initiate this tracking, we can use jQuery and an AJAX request:

  1. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>  
  2. <script type='text/javascript'>  
  3. $(function() {  
  4.     // Set the data text  
  5.     var dataText = 'page=<?php echo $_SERVER['REQUEST_URI']; ?>&referrer=<?php echo $_SERVER['HTTP_REFERER']; ?>';  
  6.   
  7.     // Create the AJAX request  
  8.     $.ajax({  
  9.         type: "POST",                    // Using the POST method  
  10.         url: "/process.php",             // The file to call  
  11.         data: dataText,                  // Our data to pass  
  12.         success: function() {            // What to do on success  
  13.             $('#complete').html( 'Your page view has been added to the statistics!' );  
  14.         }  
  15.     });  
  16. });  
  17. </script>   

Consider the above code step by step:

  • When the DOM is ready, we first set our dataText. This text is in query string format and will be sent as data to process.php, which will track this page view.
  • We then create an AJAX request that uses the POST method to send form data.
  • Our form data (dataText) is then sent to process.php in the root of our server.
  • Once this request is completed, the h2#complete element is filled with a successful notice

Our next job is to write process.php. Its main goal is to obtain information about the web statistics and store it in a database. Since our database has not yet been made, we must create a simple file, install.php, which will do this for us:

SQLite Database

  1. <?php  
  2.     # Open the database  
  3.     $handle = sqlite_open( $_SERVER['DOCUMENT_ROOT'].'stats.db', 0666, $sqliteError ) or die(  $sqliteError  );  
  4.   
  5.     # Set the command to create a table  
  6.     $sqlCreateTable = "CREATE TABLE stats(page text UNIQUE, ip text, views UNSIGNED int DEFAULT 0, referrer text DEFAULT '')";  
  7.   
  8.     # Execute it  
  9.     sqlite_exec( $handle$sqlCreateTable );  
  10.   
  11.     # Print that we are done  
  12.     echo 'Finished!';  
  13. ?>  

This code is mostly straightforward. It opens up a database (stats.db) in the root of the server and creates a database for it. The string inside $sqlCreateTable is a SQLite command that makes our statistics table. This table contains four colums: Page, IP Address, Views, and Referrer:

  • Page is a String that contains the page being viewed as a relative link (i.e. /index.php).
  • IP Address is also a String that contains a list of IP Addresses that visited this page. It is in the format of numVisits1(IP Address1) numVisits2(IP Address2) numVisits3(IP Address3) etc. For example, if we obtained 10 visits from 74.35.286.15 and 5 visits from 86.31.23.78 (hypothetical ip addresses), this String would be "10(74.25.286.15) 5(86.31.23.78)".
  • Views is an integer containing the number of times the page has been viewed.
  • Referrer is a String in the same format as IP Address. It contains all referrers to this page and how many referrals have been made.

And now onto process.php:

  1. # Connect to the database  
  2. $handle = sqlite_open( $_SERVER['DOCUMENT_ROOT'].'/stats.db', 0666, $sqliteError ) or die$sqliteError );  
  3.   
  4. # Obtain the necessary information  
  5. $page = $_POST['page'];  
  6. $referrer = $_POST['referrer'];  
  7. $ip = $_SERVER['REMOTE_ADDR'];  
  8.   
  9. # Query the database so we can update old information  
  10. $sqlGet = 'SELECT * FROM stats WHERE page = ''.$page.''';  
  11. $result = sqlite_query( $handle$sqlGet );  

This first snippet connects to our stats database and gets the information we need for the current visit. It also queries the database and obtains any information previously stored. We use this information to create an updated table.

The next job is to find old information:

Old Statistics

  1. # Set up a few variables to hold old information  
  2. $views = 0;  
  3. $ips = '';  
  4. $referrers = '';  
  5.   
  6. # Check if old information exists  
  7. if$result && ( $info = sqlite_fetch_array( $result ) ) ) {  
  8.     # Get this information  
  9.     $views = $info['views'];  
  10.     $ips = $info['ip'].' ';  
  11.     if$info['referrer'] )  
  12.         $referrers = $info['referrer'].' ';  
  13.   
  14.     # Set a flag to state that old information was found  
  15.     $flag = true;  
  16. }  

The above code finds all previous information in our table. This is vital, as we need to update the number of views (increase it by one), IP addresses, and referrers.

  1. # Create arrays for all referrers and ip addresses  
  2. $ref_num = array();  
  3. $ip_num = array();  
  4.   
  5. # Find each referrer  
  6. $values = split( ' '$referrers );  
  7.   
  8. # Set a regular expression string to parse the referrer  
  9. $regex = '%(d+)((.*?))%';  
  10.   
  11. # Loop through each referrer  
  12. foreach$values as $value ) {  
  13.     # Find the number of referrals and the URL of the referrer  
  14.     preg_match( $regex$value$matches );  
  15.   
  16.     # If the two exist  
  17.     if$matches[1] && $matches[2] )  
  18.         # Set the corresponding value in the array ( referrer link -> number of referrals )  
  19.         $ref_num[$matches[2]] = intval$matches[1] );  
  20. }  
  21.   
  22. # If there is a referrer on this visit  
  23. if$referrer )  
  24.     # Add it to the array  
  25.     $ref_num[$referrer]++;  
  26.   
  27. # Get the IPs  
  28. $values = split( ' '$ips );  
  29.   
  30. # Repeat the same process as above  
  31. foreach$values as $value ) {  
  32.     # Find the information  
  33.     preg_match( $regex$value$matches );  
  34.   
  35.     # Make sure it exists  
  36.     if$matches[1] && $matches[2] )  
  37.         # Add it to the array  
  38.         $ip_num[$matches[2]] = intval$matches[1] );  
  39. }  
  40.   
  41. # Update the array with the current IP.  
  42. $ip_num[$ip]++;  

The above two loops are very similar. They take in the information from the database and parse it with regular expressions. Once this information is parsed, it is stored in an array. Each array is then updated with the information from the current visit. This information can then be used to create the final String:

  1. # Reset the $ips string  
  2. $ips = '';  
  3.   
  4. # Loop through all the information  
  5. foreach$ip_num as $key => $val ) {  
  6.     # Append it to the string (separated by a space)  
  7.     $ips .= $val.'('.$key.') ';  
  8. }  
  9.   
  10. # Trim the String  
  11. $ips = trim( $ips );  
  12.   
  13. # Reset the $referrers string  
  14. $referrers = '';  
  15.   
  16. # Loop through all the information  
  17. foreach$ref_num as $key => $val ) {  
  18.     # Append it  
  19.     $referrers .= $val.'('.$key.') ';  
  20. }  
  21.   
  22. # Trim the string  
  23. $referrers = trim( $referrers );  

The final strings are now created. IPs and Referrers are in the form: “numVisits1(IP/Referrer1) numVisits2(IP/Referrer2) etc.” For example, the following could be the referrer String:

  1. 5(http://www.noupe.com) 10(http://css-tricks.com)  

It means that 5 referrals came from http://www.noupe.com and 10 came from http://css-tricks.com. This format saves space and is easy to parse as web statistics.

Now for the final few lines:

  1. # Update the number of views  
  2. $views++;  
  3.   
  4. # If we did obtain information from the database  
  5. # (the&nb



Blogger Image
My Blog Title

Product Engineering, software engineering company, Product Development, Product Migration, Product Re-engineering, Product Maintenance, Product Testing Commercial Application Development, Business Software development, commercial software for startups, Application Support and Maintenance, software testing Product Maintenance, Outsource product maintenance, product support and maintenance Product Migration, Product Re-engineering, product re-engineering services Product Research, Product Engineering, UI Prototyping Services Software Testing Services, Quality Assurance services, professional software testers, Load Testing, Functional Testing, Cross Platform, Browser Testing, Test Automation, Testing Tools, software quality analysis Functional Testing Services, software quality analysis, Software Testing Services, Application Testing Services, Functional Testing Types Automated Testing, Automated Testing Services, automation testing, test script development, Automation Test Tools, outsource automation testing Load Testing, Performance Testing Services, Load Testing Tools Offshore Software Development, Outsource software services, offshore outsourcing services, offshore software development services, IT outsourcing services, software quality assurance services, Offshore IT services, Custom Application Development Services, Offshore Product Engineering Benefits of IT Outsourcing, Offshore Software Development companies, offshore software development firms Outsource planning, IT outsourcing, IT development services, offshore IT companies, offshore software development Offshore Software Development, Outsource software services, offshore outsourcing services, offshore software development services, IT outsourcing services, software quality assurance services, Offshore IT services, Custom Application Development Services, Offshore Product Engineering Offshore Software Development, Outsource software services, offshore outsourcing services, offshore software development services, IT outsourcing services, software quality assurance services, Offshore IT services, Custom Application Development Services, Offshore Product Engineering