1. 程式人生 > 其它 >php實現簡單的網頁訪客統計

php實現簡單的網頁訪客統計

以下兩種方式可以實現php直接記錄網頁受訪次數,無需經過資料庫儲存資料。

方法一:

<?php
session_start();//定義session,同一IP登入不累加
$filepath = 'tongji.txt';
if ($_SESSION['temp'] == '')//判斷$_SESSION[temp]的值是否為空,其中的temp為自定義的變數
{
if (!file_exists($filepath))//檢查檔案是否存在,不存在剛新建該檔案並賦值為0
{
$fp = fopen($filepath,'w');
fwrite($fp,0);
  fclose($fp);
  counter($filepath);


}else
{
  counter($filepath);
}
$_SESSION['temp'] = 1;//登入以後,給$_SESSION[temp]賦一個值1
}
echo '歡迎光臨,您是本站第<font color="#FF0000">'.file_get_contents($filepath).'</font>位訪客';
//counter()方法用來得到檔案內的數字
function counter($f_value)
{
//用w模式開啟檔案時會清空裡面的內容,所以先用r模式開啟,取出檔案內容,儲存到變數
$fp = fopen($f_value,'r') or die('開啟檔案時出錯。');
$countNum = fgets($fp,1024);

fclose($fp);
$countNum++;
$fpw = fopen($f_value,'w');
fwrite($fpw,$countNum);
fclose($fpw);
}
//註釋下面一行可以實現同一IP登入不累加效果,測試時可以開啟
session_destroy();
?>

方法二:將以下程式碼儲存為“tongji.php”

<?php
$n=file_get_contents('tongji.txt');
$n++;
file_put_contents('tongji.txt',$n);
echo "document.write($n);";
?>

資料使用方式:

你是第<script type=text/javascript src="tongji.php"></script>位訪問者