Tuesday, 8 March 2022

PHP#33MySQL#29 - Đếm lượt truy cập (KẾT THÚC KHÓA HỌC)

//hitcounter.php
<?php
session_start(); 
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<?php 
include("../connect.php");
//cập nhật số luowhtj truy cập:
$sl="update counter set cnt=cnt+1";
mysqli_query($link,$sl);
//Lấy dữ liệu số lượt truy cập để hiển thị ra web:
$sl2="select * from counter";
$kq=mysqli_query($link,$sl2);
$d=mysqli_fetch_array($kq);

//Định dạng:
$chuoi=str_pad($d['cnt'],6,"0",STR_PAD_LEFT);
$luottrycap="";
for($i=0;$i<strlen($chuoi);$i++)
{
$tam=substr($chuoi,$i,1);
$luottrycap.="<img src='images/$tam.png'/>";
}

/*-Khi user truy cập vào website:
+lần đầu tuy cập: Lưu thông tin của user lên csdl
+Sau lần đầu tiên: cập nhtaaj lastvisit
- Xóa các dòng dữ liệu quá 1 phút (Quy ước thời gian để khẳng định online hay offline: 1 phút)
- Thống kê số liệu người dùng online, thành viên online, khác online*/
$id=session_id();
$timeout=60; //1 phút
if(isset($_SESSION['iduser']))
$user=$_SESSION['iduser'];
else $user="";
//$lastvisited=time(); //unix_timestamp()
//Kiểm tra user có trên csdl chưa:
$sl1="select * from user_online where id='$id'";
$kq1=mysqli_query($link,$sl1);
if(mysqli_num_rows($kq1))
{
//Đã có trong csdl thì cập nhật lại tông tin:
$sl2="select * from user_online set lastvisit=unix_timestamp(), user='$user' where id='$id'";
mysqli_query($link,$sl2);
}
else{
//Chưa có trong csdl thêm mới:
$sl2="insert into user_online values('$id',unix_timestamp(),'$user')";
mysqli_query($link,$sl2);
}

//Xóa những dòng đã quá thời gian quy ước:
$sl3="delete from user_online where unix_timestamp()-lastvisit > $timeout";
mysqli_query($link,$sl3);

//Thống kê tổng số người online:
$sl4="select count(*) as tongso from user_online";
$kq4=mysqli_query($link,$sl4);
$d4=mysqli_fetch_array($kq4);
//Định dạng:
$chuoi=str_pad($d4['tongso'],3,"0",STR_PAD_LEFT);
$tongso="";
for($i=0;$i<strlen($chuoi);$i++)
{
$tam=substr($chuoi,$i,1);
$tongso.="<img src='images/$tam.png'/>";
}

//Thống kê số thành viên online:
$sl5="select count(*) as souser from user_online where user!=''";
$kq5=mysqli_query($link,$sl5);
$d5=mysqli_fetch_array($kq5);
?>
<div>Lượt truy cập: <?php echo $luottrycap;?></div>
<div>Tổng sô người online: <?php echo $tongso;?></div>
<div>Sô thành viên online: <?php echo $d5['souser'];?></div>
</body>
</html>

//test_user.php
<?php 
session_start();
$_SESSION['iduser']=1;
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
</body>
</html>

0 comments:

Post a Comment