PHP Page Visit Counter with Sessions for Website
- PHP page view counter for website
- PHP page visit counter with sessions for website
- PHP page view counter for anywhere
This page will help you create a PHP Page Visit Counter with Sessions for Website. You can use it for a website but don't use it for a bunch of websites since the page names may be the same on two or more sites-then you will get data cross-contamination, unless you name the database tables something different for each site and change the on-page scripts to reflect this change. Why didn't we use the GD Library? We know of no other way to do it except using that library if someone has a counter on a plain old HTML web page, but you don't need the library if you want a counter on a PHP page or on an HTML page that's on a site where you've set up the htaccess file so the PHP parser runs on all HTML and HTM pages as well as PHP pages. Usually the following will suffice in your htaccess file:
RemoveHandler .html .htm
AddType application/x-httpd-php .php .htm .html
So if either of these are true (PHP page or HTML page that's on a site where you've made HTML and HTM parse PHP), you need not use the GD Library. The issue here is that the counter is written in PHP and a standard HTML or HTM page is not set up to parse PHP script, which is why most webmasters simply use the PHP extension (which you can use on HTML pages whether or not there is PHP on them) to get PHP parsing to occur on the server before the page is sent to the browser. You can put links to PHP files on HTML pages, but counters need to automatically function, not require a link click. You can use various includes on HTML pages but if they are the PHP kind, you need to use the htaccess method above to get your server to okay it, so this doesn't change the basic requirement: Get the server parsing PHP on the counter pages or use PHP page view counter for anywhere, which uses GD. You can't expect people to rename web pages to the PHP extension just to get a counter (but there's no reason why they cannot leave their extensions alone and use the htaccess trick above so their pages can handle PHP counter code).
You can use the script below on any PHP page or HTML page that parses PHP, as long as the server the script and counter are on supports MySQL and PHP. Make sure the entire PHP script below is used, and put your other page content after the final ?> tag and before the closing body tag. Check out the CSS part of the script. The positioning of the class called counter should be adjusted according to your needs, and you may surely make the counter fancier or superimpose counter numbers on a counter image, or whatever. Add more CSS here if needed. The page title should be changed to your page title, external .js and .css scripts linked to, keyword and description metatags added, etc.
This script uses PHP and MySQL. If you don't know about MySQL, now is a good time to learn. You'll be able to go to phpAdmin in your cPanel X control panel and see the page visit totals.
Let's look at the script code: We start with session_start() to get a session started. This is so page refreshing will have no effect for 24 minutes. How do we figure 24 minutes? Find out if you have sessions enabled by saving the tiny code block below as s.php in your website public_html folder and running it: http://yoursite.com/s.php. If there is a sessions section and you see the word "enabled" in the sessions section, you're in business. Look for the directive session.gc_maxlifetime in the sessions section. We found 1440. This many seconds is 24 minutes.
<?php
phpinfo();
?>
Next we get ready to access the MySQL database by using the include with config.php in it, then we get the page's URI from the $_SERVER["REQUEST_URI"] function and do a bit of input filtering, cleaning it up with htmlspecialchars()-otherwise it poses a cross-site scripting vulnerability. The URI will look like this: /folder/subfolder/page-that-the-counter-is-on.php.
Now we create a MySQL table named counter if it doesn't already exist. It contains the fields id (since we need a primary field or MySQL will scream), webpage, and visitors (to tally up the page views). The webpage field can be up to 90 characters long but if you have longer ones, change the table's allotment. With this unique value (you only have one page named this on your site), we will recognize incoming visitors' data as specifically related to this page, and add to the total. Or start a new record because no record pertaining to this page exists. And that's our next step. We use the MySQL SELECT statement to look for the web page record for the page that we got above with the $_SERVER["REQUEST_URI"] function. Then we use the mysql_num_rows() function to determine if the page was found in the counter table. If not, we INSERT the webpage name (with folders if they exist) in the table with a 1 for how many visitors. If we want to fix it so refresh increments the counter, we are talking about views. PHP page view counter for anywhere uses no sessions to deal with visits instead of views, so its data is views.
But if we DO find the page in the db table, we add to its visitors tally using visitors=visitors+'1' in an UPDATE, after checking our session variables first, and if the variable isn't set we set it and increment visitors, but if it is set we do nothing now. MySQL doesn't seem to mind if we increment a field this way, without first getting the old value into a PHP variable, incrementing it, and sticking this new value back in the database table.
Back to the code: Next we read the table again, get the visitors tally using the PHP mysql_fetch_assoc() function and the use of the associative key "visitors", and find the length of this string of digits, subtracting that from 9. This is the correct number of zeros to concatenate with the number in order to always get a 9-digit number (e.g., 000001234). This makes the counter look better on the web page. So we do the concatenating, putting the word "Counter: " first (optional, but it clarifies that the number is indeed a counter. Now we close the db. Note that there are 2 commented out PHP functions: //session_unset(); and //session_destroy();, and if you un-comment them a page refresh will increment the counter, but leave them as they are and you'll wait 24 minutes (or whatever your server's setting is).
On to the code for the script. Name the following: counter.php
<?php
session_start();
include_once"../config.php";
$webpage=htmlspecialchars($_SERVER["REQUEST_URI"]);
$sql = "CREATE TABLE IF NOT EXISTS counter (
id int(4) NOT NULL auto_increment,
webpage varchar(90) NOT NULL,
visitors int(11) NOT NULL default '1',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
mysql_query($sql);
$result=mysql_query("SELECT * FROM counter WHERE webpage='$webpage'");
$num_rows = mysql_num_rows($result);
if ($num_rows == 0){
mysql_query("INSERT INTO counter (id, webpage, visitors)
VALUES ('','$webpage','1')");
}else{
if (!isset($_SESSION['webpage'])){$_SESSION['webpage'] = 0;
mysql_query("UPDATE counter SET visitors=visitors+'1' WHERE webpage='$webpage'");}}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Counter</title>
<style type="text/css">
BODY {margin-left:0; margin-right:0; margin-top:0;text-align:left;background-color:#ddd;font:bold 13px Verdana; color:black;}
.counter {position:absolute;top:200px;left:200px;background-color:#bbb;border:4px solid blue;padding:3px;text-align:center}
</style>
</head>
<body>
<?php
$result=mysql_query("SELECT * FROM counter WHERE webpage='$webpage'");
$row=mysql_fetch_assoc($result);
$n=$row['visitors'];
$l=9-strlen($n);
$z=substr('000000000',0,$l);
$c="Counter: ".$z.$n;
echo "<div class='counter'>".$c."</div>";
mysql_close();
//session_unset();
//session_destroy();
?>
</body>
</html>