0% found this document useful (0 votes)
81 views6 pages

Hit Counter Tutorial

This document provides instructions for adding a PHP and MySQL hit counter to count page views on a website. It describes setting up a MySQL database with a table to store the page URLs and hit counts. It then explains using phpMyAdmin to define the database and table structure. Finally, it discusses using PHP scripts to connect to the database, retrieve the HTTP referer header to identify the page being viewed, and update the hit count for that page in the database. The goal is to have invisible elements like images or iframes link to the PHP script, which can then count views to other pages without users directly interacting with the counting script.

Uploaded by

redmosquito
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views6 pages

Hit Counter Tutorial

This document provides instructions for adding a PHP and MySQL hit counter to count page views on a website. It describes setting up a MySQL database with a table to store the page URLs and hit counts. It then explains using phpMyAdmin to define the database and table structure. Finally, it discusses using PHP scripts to connect to the database, retrieve the HTTP referer header to identify the page being viewed, and update the hit count for that page in the database. The goal is to have invisible elements like images or iframes link to the PHP script, which can then count views to other pages without users directly interacting with the counting script.

Uploaded by

redmosquito
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Adding A PHP+MySQL Hit Counter to your Website

Setting up MySQL

First off, decide what you want to keep track of. In this case, lets commit to tracking total number of hits on each of a number of web pages. So, well want to know the URL of the page and the number of hits it received. An URL is basically text, but the count is a number.

URL count http://student.. 165 http://quick 12

We could use a PHP script to define the database, but since we would only run that script once, it might be easier to define it by hand using phpMyAdmin (PMA). So we point our browser at our (already installed) PMA site


We can use the Create new database entry to start a new database. Since this is a shared server, I ask students to use your UWNETID for the database name. Thatll bring us to the screen shown below. Its pretty typical PMA screen, with global navigation stuff on the left, task options at the top, a place where it shows the SQL query that just got executed (in this case the command was create database netid) below that, and the actual work area at the bottom right (where it says Create new table on database netid).


Type in a name. Lets use hit_counter as the name (no spaces!) and we just want two columns (or fields) so put a 2 in there, then click the Go button in the lower right corner. The central part of the next screen is shown below. There are two columns of prompts, one for each of our two columns of data. The screen dump shows how you would fill them in.
Hit Counter Tutorial.docx Page 1 of 6


The radio-buttons at the bottom indicate that the url field is a primary key, which means we plan to use it to access or sort data in the future. (MySQL will keep track of indexing data to enable quick access, but we can still use any field in a command, it just might take longer.) Below is what youll see when you hit the Save button.


Hit Counter Tutorial.docx Page 2 of 6

At this point the database is completely defined and ready to use. We could use the PMA interface to view the data or load data (see the Browse and Insert tabs at the top?). The Action menu items (see below) allow us to Browse (view), Edit, and Delete rows of data from the tables as well. However, its time for us to switch to HTML and PHP

The PHP
So, theres this netid database on the 128.95.103.44 server and it has a hit_counter table in it. We need some PHP that is able to query and modify that database. We dont need to go into all the details of doing this, but suffice it to say we have to create an ID and a PW for accessing the database. As this is sort of secret info, the convention is to place it in a separate file and include it into our PHP page. That way, if we print out the PHP, we dont have to reveal the secret info. That file might look like this: File dbconnect.php
<?php $hostname = "128.95.103.44"; $database = "netid"; $username = "arch482"; $password = "xxxxxxx"; // use the class password here, not the xxxxxxs $Cdb = mysql_connect($hostname, $username, $password) or die(mysql_error() . mysql_errno()); mysql_select_db($database, $Cdb); ?>

The first few lines simply define variables for the database host, and the names, etc. The last few lines ask PHP to open the connection from our computer to the database host, and specify the name of the database to connect to. Its important to note that $Cdb gets defined at this time. Well use that later. Now for a bit of thinking webishly We want to build a script that counts accesses not to itself, but to OTHER files. The secret is to remember that every time a web page is accessed, including the PHP scripts, the URL of the referring page (the one were coming from) is part of the information available (thats called the HTTP_Referer). So if we had an anchor that linked from the HTML page we wanted to count to our script, the HTTP_Referer would be the URL of the page we want to count. But we cant just put a click to be counted anchor on the page. Nobody would. But wait! HTML references to things like images and iframes are automatically followed to get their contents! So if we included an img tag in the HTML, it would load automatically. And its perfectly legal to write
<img src=counter.php>

Well have to make sure some image data gets sent back for this to work, but the HTML abov will cause the server to run our script, and the HTTP_Referer will be the URL of the page containing that <img> tag. Now lets see what the counter script itself looks like.

Hit Counter Tutorial.docx

Page 3 of 6

File counter.php
<?php ini_set('display_errors','1'); ini_set('display_startup_errors','1'); error_reporting (E_ALL); include(dbconnect.php'); $url = $_SERVER["HTTP_REFERER"]; // set up enhanced error reporting

// connect to database

// ask where we came from // ask db if weve got a count $query = "Select count from hit_counter where url=\"$url\""; $result = mysql_query($query, $Cdb); $nRows = mysql_num_rows($result); // How many rows matched? // (should be 0 or 1) if( $nRows == 0 ){ // Never counter before? Add it $n = 1; $query = "insert into hit_counter values (\"$url\",$n)"; } else { // Counted? Update count list($n) = mysql_fetch_array( $result ); // first, get the old count $n = $n + 1; // increment the count. $query = "update hit_counter set count = $n where url=\"$url\""; } mysql_query($query, $Cdb); header("Location: smiley.gif"); ?>

Heres what happens in this script


The first three lines set up enhanced error reporting (just in case). Then we ask for a connection to the database. Next we pull the needed HTTP_Referer data from the server environment. Using that, we build a query to the database, selecting all records where the url field matches the referring URL. That should produce one row if were already counting that URL or 0 if weve never seen it before, so we ask (mysql_num_rows) how many rows we got back from our query and then test to see if we got 0 rows or more. If we got 0 rows, we need to add this url to the table, so build a query to do that. Otherwise, if we got 1 row, we need to update it by adding 1 to the old value, so build a query to do that. Whichever query we built, send it to MySQL. Assume all went well. At the very end, send a redirect to the browser, telling it to load the smiley.gif image, then terminate the script. Were done.

The HTML
There really isnt much left to say. The HTML page treats the hit counter as an image File be_counted.html
<!doctype html> <html> <head> <title>I am counted</title> </head> <body> <h1>Hit Counter Demo</h1> <img src="counter.php"> </body> </html>
Hit Counter Tutorial.docx Page 4 of 6

But what if
Indeed, what if you wanted to SEE the total page views .? Heres alternative script and HTML code to do that. File show_counter.php
<?php include(dbconnect.php'); $url = $_SERVER["HTTP_REFERER"]; $query = "Select count from hit_counter where url=\"$url\""; $result = mysql_query($query, $Cdb); $nRows = mysql_num_rows($result); if( $nRows == 0 ){ $n = 1; $query = "insert into hit_counter values (\"$url\",$n)"; } else { list($n) = mysql_fetch_array( $result ); $n = $n + 1; $query = "update hit_counter set count = $n where url=\"$url\""; } mysql_query($query, $Cdb); print"<h3>$n</h3>"; ?> // poor HTML, but should work

File show_counter.html
<!doctype html> <html> <head> <title>I am counted</title> </head> <body> <h1>Hit Counter Demo</h1> <p>This page contains an iframe that demonstrates one way you might deploy a hitcounter script.</p> <p>Page views: <iframe style="position:relative;top:5" src="counter.php" width=50 height=30 scrolling=no frameborder=0></p> <p>To add a page counter to your page, add the HTML for the page:<br> <tt>&lt;iframe style="position:relative;top:5" src="http://quicksilver.be.washington.edu/counter_demo/show_counter.php" width="50" height="30" scrolling="no" frameborder="0"&gt;</tt> </body> </html>

Hit Counter Tutorial.docx

Page 5 of 6


http://quicksilver.be.washington.edu/counter_demo/be_counted.html

http://quicksilver.be.washington.edu/counter_demo/show_counter.html


Hit Counter Tutorial.docx Page 6 of 6

You might also like