您的位置:首页 > 编程语言 > PHP开发

基于PHP文件操作实现页面统计

2015-07-28 11:23 711 查看
假如页面统计只需要记录统计数值,不记录其他具体的数据时,这时没有必要使用数据库进行记录,可以直接将统计数值存放到文本文件中。当然,这不是最好的方式,不过这是最简单的方式。

index.html

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no" name="format-detection">
<meta content="email=no" name="format-detection">
<title>statistics</title>
<style>
html, body{
width: 100%;
margin: 0;
padding: 0;
overflow-x: hidden;
overflow-y: auto;
font-family: 'Microsoft Yahei';
text-align: center;
}
.btn{
width: 30%;
height: 30px;
line-height: 30px;
border-radius: 4px;
background-color: #428bca;
font-size: 18px;
display: inline-block;
}
</style>
</head>
<body>
<h1>页面统计</h1>
<div class="btn" id="btn_click">点击</div>
<div class="btn" id="btn_forward">转发</div>
<script>
var btn_click = document.querySelector('#btn_click'),
btn_forward = document.querySelector('#btn_forward'),
hasTouch = 'ontouchstart' in window;
tapend = hasTouch ? 'touchend' : 'mouseup';
btn_click.addEventListener(tapend, function(){
statistics('click');
}, false);
btn_forward.addEventListener(tapend, function(){
statistics('forward');
}, false);
function statistics(action){
var url = 'http://localhost/statistics/interfaces/statistics.php?action='+action,
script = document.createElement('script');
script.setAttribute('src', url);
document.querySelector('head').appendChild(script);
}
</script>
</body>
</html>


statistics.php

<?php

$action = @$_GET['action'];

function statistics($action){
$filename = $action.'_statistics.txt';
if(file_exists($filename)){
$count = file_get_contents($filename);
file_put_contents($filename, ++$count);
}else{
file_put_contents($filename, 1);
}
}

if($action === 'click'){
statistics('click');
}else if($action === 'forward'){
statistics('forward');
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: