使用 PHP 和 MySQL 进行网站统计






4.67/5 (11投票s)
使用 PHP 和 MySQL 进行网站统计
引言
记录访问次数和唯一访客数量,并将结果以数字和图表的形式显示,如下所示

背景
我使用 PHP 编写了所有代码来实现此功能,并使用 MySQL 来管理其数据。对于图表,我使用了 PHPGraphLib 模块。
最初,我使用一个 PHP 图形点击计数器 来统计网站的访问量,该计数器将数据存储在服务器上的文件中。但后来我逐渐将其完全更改为将数据存储在 MySQL 数据库中,同时保留其图形数字显示技术。我还扩展了相同的模块来统计访问次数和唯一访客数量。在使用此代码之前,您需要了解 PHP 图形点击计数器和 PHPGraphLib 的使用方法。
代码文件
该项目包含三个主要文件:count.php,graph.php 和 index.php。
count.php
此文件包含所有访问数据库和显示图形数字的代码
<?php
include("configuration.php");
/* Get page and log file names */
$page = input($_GET['page']) or die('ERROR: Missing page ID');
$timestampInSeconds = $_SERVER['REQUEST_TIME'];
$mySqlDateTime= date("Y-m-d H:i:s", $timestampInSeconds);
$sql = 'INSERT INTO '.$tableName.'(`id`, `Section`, `Date`, `IP`)
VALUES (NULL, \''.$page.'\',\''.$mySqlDateTime.'\', \''.$_SERVER['REMOTE_ADDR'].'\');';
mysql_select_db($database, $con);
mysql_query($sql);
$query='SELECT COUNT( * ) total FROM '.$tableName.' where section=\''.$page.'\'';
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_NUM);
$count = $row[0];
$query='SELECT count(distinct IP) FROM '.$tableName.' where section=\''.$page.'\'';
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_NUM);
$UniaquCount = $row[0];
mysql_close($con);
/* Get style and extension information */
$style = input($_GET['style']) or $style = $default_style;
$style_dir = 'styles/' . $style . '/';
$ext = input($_GET['ext']) or $ext = $default_ext;
$count = $count + 1;
if ($min_digits > 0)
$count = sprintf('%0'.$min_digits.'s',$count);
/* Print out Javascript code and exit */
echo 'document.write(\' Vists: \');';
$len = strlen($count);
for ($i=0;$i<$len;$i++)
echo 'document.write(\'<img src="'.$base_url . $style_dir . substr(
$count,$i,1) . '.' . $ext .'" border="0">\');';
echo 'document.write(\'<br>\');';
echo 'document.write(\'Vistors: \');';
$len = strlen($UniaquCount);
for ($i=0;$i<$len;$i++)
echo 'document.write(\'<img src="'.$base_url . $style_dir . substr(
$UniaquCount,$i,1) . '.' . $ext .'" border="0">\');';
exit();
?>
graph.php
此文件包含生成数据图形表示的代码
<?php
include("configuration.php");
$page = input($_GET['page']) or die('ERROR: Missing page ID');
$query='SELECT date, count(*),
count(distinct IP) FROM `'.$tableName.'`
where section=\''.$page.'\' group by date order by date';
$result=mysql_query($query) or die('Query failed: ' . mysql_error());
$fields=mysql_num_fields($result);
$num=mysql_numrows($result);
$loopCounter = 0;
$data = array();
$data2 = array();
while($ris=mysql_fetch_row($result))
{
$data[$ris[0]]=$ris[1];
$data2[$ris[0]]=$ris[2];
}
mysql_close($con);
include("phpgraphlib.php");
$graph=new PHPGraphLib(600,250);
$graph->addData($data,$data2);
$graph->setTitle("Site Statistics");
$graph->setBars(false);
$graph->setLine(true);
$graph->setDataPoints(true);
$graph->setDataPointColor("maroon");
$graph->setDataValues(true);
$graph->setDataValueColor("maroon");
$graph->setGoalLine(.0025);
$graph->setGoalLineColor("red");
$graph->setXValuesHorizontal(true);
$graph->createGraph();
?>
index.php
此文件包含调用 count.php 和 graph.php 并将结果显示在浏览器中的代码
<?php include("configuration.php"); ?>
<script language="Javascript"
src="<?php echo $base_url;?>count.php?page=<?php echo $_REQUEST['section'];?>">
</script>
<?php
echo "<br>";
echo '<img src="'.$base_url.'graph.php?page='.$_REQUEST['section'].'" />';
?>
Using the Code
下载源代码 zip 文件,并将其解压缩到服务器上的一个文件夹中。创建数据库表
您需要在 MySQL 数据库中创建一个简单的表,方法是执行以下脚本
CREATE TABLE countdetail (
Id int(11) NOT NULL AUTO_INCREMENT,
Section varchar(500) NOT NULL,
`Date` date NOT NULL,
IP varchar(50) DEFAULT NULL,
PRIMARY KEY (Id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
配置项目
第一步,您需要配置项目。在 configuration.php 文件中设置其基本 URL 和数据库参数
<?php
// SETUP YOUR COUNTER
// URL of the folder where script is installed. INCLUDE a trailing "/" !!!
$base_url = 'https:///MySites/Counter/';
// database parameters
$username="root";
$password="";
$servername="localhost";
$database="mysite";
$tableName="countdetail";
// Optional parameters, if not sure leave with default values
// Default image style (font)
$default_style = 'web1';
// Default counter image extension
$default_ext = 'gif';
// Minimum number of digits shown (zero-padding). Set to 0 to disable.
$min_digits = 0;
// Don't change anything below
/* Turn error notices off */
error_reporting(E_ALL ^ E_NOTICE);
$con = mysql_connect($servername,$username,$password);
if (!$con)
die('Cannot dadd comments at the moment');
else
@mysql_select_db($database) or die( "Unable to select database");
/* This function handles input parameters making sure
nothing dangerous is passed in */
function input($in) {
$out = htmlentities(stripslashes($in));
$out = str_replace(array('/','\\'), '', $out);
return $out;
}
?>
查看结果
现在是时候查看结果了,打开浏览器并输入服务器上 index.php 文件的地址,以及要统计访问量的页面名称。例如
其中 "yourSiteName" 是您的页面名称。如果一切正常,应该会显示与本文顶部相同的结果。
值得关注的点
您可以轻松地构建一个具有良好界面的计数器,并在任何其他网站中调用它以记录该网站的数据。在我的博客之一上查看此代码的实际运行效果...