Publishing System Settings Logout Login Register
Monitor Hits to your site and MORE.. Using PHP and SQL!
TutorialCommentsThe AuthorReport Tutorial
Tutorial Avatar
Rating
Add to Favorites
Posted on January 31st, 2007
8503 views
PHP Coding
Create A System For Your Site To Monitor Hits, Unique Hits and where everyone is!


I originally wrote this tutorial for Pixel2Life forums, I have decided to rewrite it and publish it.

Lets get started!

Firstly, if you don't already have one.. create a blank file and call it config.php

Put this in it:

[code=PHP]<?php

$connect = mysql_connect( 'localhost', 'DATABASE USERNAME', 'DATABASE PASSWORD' ) or die(mysql_error()); // Connect to MySQL.

mysql_select_db( 'DATABASE NAME' ); // Select the database.

function _ip( )
{
    return ( preg_match( "/^([d]{1,3}).([d]{1,3}).([d]{1,3}).([d]{1,3})$/", $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'] );
}

$ip = _ip(); // Get the users IP using the function above
$time = date( 'd-m-Y' ); // Get the current date, in the format of: 12-12-2006
$timestamp = time();

?>[/code]

In order to connect to the database, you need to fill in your database details.

Next we need to create the table..
[code=SQL]
CREATE TABLE `stats` (
  `ip` varchar(20) NOT NULL default '',
  `date` varchar(10) NOT NULL default '00-00-0000',
  `hits` int(10) NOT NULL default '1',
  `online` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
[/code]

Run that in PHPmyadmin.

Next we want to have the code which updates the database with new stats, when a new visitor / hit is made.

Create a new file, call it hit.php

[code=PHP]
<?php

require_once 'config.php'; // Include config file.

$getStats = mysql_query("SELECT * FROM `stats` WHERE `ip` = '" . $ip . "' && `date` = '" . $time . "'") or die(mysql_error());

if( mysql_num_rows( $getStats ) == 0 )
{
    $select = mysql_query("INSERT INTO `stats` (`ip`, `date`, `hits`, `online`) VALUES ('" . $ip . "', '" . $time . "', '1', '" . $timestamp . "')") or die(mysql_error());
}
else
{
    $select = mysql_query("UPDATE `stats` SET `hits` = `hits`+1, `online` = '" . $timestamp . "' WHERE `ip` = '" . $ip . "' && `date` = '" . $time . "'");
}
?>
[/code]

Instead of explaining each part, I have commented my code.

That will now either update the visitors hit count, or insert a new row for their IP.

--

To show the stats, we need to create a new file.

Create a blank file called stats.php

Put this in it:

[code=PHP]
<?php

require_once 'config.php'; // Include config file.
require_once 'hit.php'; // Record the hits to this page

$selectHits = mysql_query("SELECT * FROM `stats` WHERE `date` = '" . $time . "' GROUP BY `ip`") or die(mysql_error()); // Select stats from today
 
$uniqueToday = mysql_num_rows($selectHits); // Count uniques today
$hitsToday = mysql_result(mysql_query("SELECT SUM(`hits`) as total FROM `stats` WHERE `date` = '" . $time . "' GROUP BY `date`"), 0, "total"); // Count total hits today

$totalUHits = mysql_result(mysql_query("SELECT COUNT(`hits`) FROM `stats`"), 0); // Count total unique hits
$totalHits = mysql_result(mysql_query("SELECT SUM(`hits`) as total FROM `stats`"), 0, "total"); // Count total hits

$diff = time() - 300;
$countOnline = mysql_query("SELECT * FROM `stats` WHERE `online` > '" . $diff . "'") or die(mysql_error());
$countOnline = mysql_num_rows($countOnline);



?>

<!-- Echo stats below -->
Unique Visits Today: <?php echo $uniqueToday ?><br />
Hits Today: <?php echo $hitsToday ?><br />
<br />
Total Unique Visits: <?php echo $totalUHits ?><br />
Total Hits: <?php echo $totalHits ?><br />
<br />
Guests Online: <?php echo $countOnline ?><br />
<br />
[/code]

Code commented, instead of explaining.

That's it! We are done!!

This has been tested, and works just fine.

A extra feature that was requested, was to see what page a user is currently viewing. I did not want to intergrate this into the main script, so you can find the new script with this feature on the next page.



The same script with an extra feature, as explained on the previous page found below.

To make this work, follow the instructions on the page before.. then follow these simple steps:

Run this SQL query in PHPmyAdmin:

[code=SQL]
ALTER TABLE `stats` ADD `page` VARCHAR( 255 ) NOT NULL ;
[/code]

Then we need to update a few pages...

Change hit.php to:

[code=PHP]
<?php

require_once 'config.php'; // Include config file.

$page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

$getStats = mysql_query("SELECT * FROM `stats` WHERE `ip` = '" . $ip . "' && `date` = '" . $time . "'") or die(mysql_error());

if( mysql_num_rows( $getStats ) == 0 )
{
    $select = mysql_query("INSERT INTO `stats` (`ip`, `date`, `hits`, `online`, `page`) VALUES ('" . $ip . "', '" . $time . "', '1', '" . $timestamp . "', '" . $page . "')") or die(mysql_error());
}
else
{
    $select = mysql_query("UPDATE `stats` SET `hits` = `hits`+1, `online` = '" . $timestamp . "', `page` = '" . $page . "' WHERE `ip` = '" . $ip . "' && `date` = '" . $time . "'");
}
?>
[/code]

Now we need to update stats.php, this code is rather long...

[code=PHP]
<?php

require_once 'config.php'; // Include config file.
require_once 'hit.php'; // Record the hits to this page

$diff = time() - 300; // Shows users online in past 3 minutes

if( isset( $_GET['showonline'] ) && $_GET['showonline'] == '1' ) // Does the user want to see who is viewing which page?
{ // If so...
    $countOnline = mysql_query("SELECT * FROM `stats` WHERE `online` > '" . $diff . "' ORDER BY `online` ASC") or die(mysql_error()); // Select online users
   
    if( mysql_num_rows( $countOnline ) == '0' )
    {
        echo 'There is currently no one online.';
    }
    else
    {
        echo 'What pages are people viewing? <br /><br />';
       
        while( $user = mysql_fetch_array( $countOnline ) )
        {
            echo $user['ip'] . ' is currently viewing: <a href="' . $user['page'] . '">This Page</a> <br />';
        }
    }
           
}
else // If not...
{

$selectHits = mysql_query("SELECT `ip` FROM `stats` WHERE `date` = '" . $time . "' GROUP BY `ip`") or die(mysql_error()); // Select stats from today
 
$uniqueToday = mysql_num_rows($selectHits); // Count uniques today
$hitsToday = mysql_result(mysql_query("SELECT SUM(`hits`) as total FROM `stats` WHERE `date` = '" . $time . "' GROUP BY `date`"), 0, "total"); // Count total hits today

$totalUHits = mysql_result(mysql_query("SELECT COUNT(`hits`) FROM `stats`"), 0); // Count total unique hits
$totalHits = mysql_result(mysql_query("SELECT SUM(`hits`) as total FROM `stats`"), 0, "total"); // Count total hits

$countOnline = mysql_query("SELECT `ip` FROM `stats` WHERE `online` > '" . $diff . "'") or die(mysql_error()); // Select online users
$countOnline = mysql_num_rows($countOnline); // Count online users



?>

<!-- Echo stats below -->
Unique Visits Today: <?php echo $uniqueToday ?><br />
Hits Today: <?php echo $hitsToday ?><br />
<br />
Total Unique Visits: <?php echo $totalUHits ?><br />
Total Hits: <?php echo $totalHits ?><br />
<br />
Guests Online: <a href="stats.php?showonline=1"><?php echo $countOnline ?></a><br />
<br />

<?php
}
?>
[/code]

And thats it!

Thanks for reading.

Hopefully this script comes in useful, Enjoy. Don't forget to check out my other tutorials!
Dig this tutorial?
Thank the author by sending him a few P2L credits!

Send
Adam

This author is too busy writing tutorials instead of writing a personal profile!
View Full Profile Add as Friend Send PM
Pixel2Life Home Advanced Search Search Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Pixel2life Homepage Submit a Tutorial Publish a Tutorial Join our Forums P2L Marketplace Advertise on P2L P2L Website Hosting Help and FAQ Topsites Link Exchange P2L RSS Feeds P2L Sitemap Contact Us Privacy Statement Legal P2L Facebook Fanpage Follow us on Twitter P2L Studios Portal P2L Website Hosting Back to Top