星期三 , 22 1 月 2025

PHP网站记录用户点击和点击数

当页面刷新只记录一次的方法

<?php
// Database connection details
$host = 'your_host';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';

// Create a connection
$conn = new mysqli($host, $user, $pass, $db);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get user IP address
$ip_address = $_SERVER['REMOTE_ADDR'];

// Check if this IP has visited in the last 30 minutes
$stmt = $conn->prepare("SELECT visit_time FROM page_hits WHERE ip_address = ? ORDER BY visit_time DESC LIMIT 1");
$stmt->bind_param("s", $ip_address);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($visit_time);

if ($stmt->num_rows > 0) {
    $stmt->fetch();
    // Check if the last visit was more than 30 minutes ago
    if (time() - strtotime($visit_time) > 1800) {
        // Insert the new hit into the database
        $stmt = $conn->prepare("INSERT INTO page_hits (ip_address) VALUES (?)");
        $stmt->bind_param("s", $ip_address);
        $stmt->execute();
    }
} else {
    // No previous visit from this IP, insert the hit
    $stmt = $conn->prepare("INSERT INTO page_hits (ip_address) VALUES (?)");
    $stmt->bind_param("s", $ip_address);
    $stmt->execute();
}

// Count the total number of hits
$result = $conn->query("SELECT COUNT(*) AS hits FROM page_hits");
$row = $result->fetch_assoc();
echo "This page has been visited " . $row['hits'] . " times.";

$conn->close();
?>