How to implement recording browsing history in PHP?

To achieve recording browsing history, you can follow these steps:

  1. Create a database table to store browsing history, including fields like id (record ID), user_id (user ID), page_url (page URL), visit_time (time of visit), etc.
  2. Store the URL of the page the user accesses and the current time in the browsing history table in the logic code of each page. You can use the INSERT statement to insert data, for example:
$user_id = $_SESSION['user_id']; // 获取当前用户ID
$page_url = $_SERVER['REQUEST_URI']; // 获取当前页面URL
$visit_time = date('Y-m-d H:i:s'); // 获取当前时间

$sql = "INSERT INTO browsing_history (user_id, page_url, visit_time) VALUES ('$user_id', '$page_url', '$visit_time')";
  1. When it is necessary to display browsing history, the corresponding records can be retrieved from the database based on the user ID, sorted in descending order by time, for example:
$user_id = $_SESSION['user_id']; // 获取当前用户ID

$sql = "SELECT * FROM browsing_history WHERE user_id = '$user_id' ORDER BY visit_time DESC";
$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_assoc($result)) {
    // 显示每条历史记录的信息
    echo $row['page_url'] . ' - ' . $row['visit_time'] . '<br>';
}

Note: the ‘$conn’ in the above code is a database connection object that needs to be initialized according to the actual situation.

Additionally, to protect user privacy and enhance performance, appropriate optimizations can be made based on actual needs, such as setting a maximum number of browsing history records and regularly clearing out expired records.

广告
Closing in 10 seconds
bannerAds