首页 > 解决方案 > 将计时器添加到简单的 php 登录时间

问题描述

我想知道如何在一个简单的 php 登录表单中添加一个计时器,以显示用户保持登录的时间(优先级)

如果你不介意,你能告诉我如何将时间乘以每小时的价格率吗

例如:Mr Q 登录 3 小时,价格为 2 美元,所以主页会在计时器旁边显示总计 6 美元

标签: phptimerlogin-script

解决方案


使用会话变量跟踪持续时间。当用户登录时,记录时间并将其粘贴到会话变量中。这只会在登录时发生,并且在他们注销时会被删除。

每次刷新页面时,获取当前时间和会话时间戳之间的差异 - 然后进行乘法以获取成本。

<?php
// session_start(); goes at the top of any page where you need to create or access session variables
session_start(); // you have to tell PHP to start the session before you add a session variable 

function login() {
  // do logic and log in the user
  // set a session variable
  if ($logged_in) {
    $_SESSION['logged_in_time'] = time();
  }
}

function logout() {
  // do logic and log OUT the user
  // clear the session variable
  unset($_SESSION['logged_in_time']);
}

然后在你的 header.php (或任何面向 php 页面的 UI)

<?php 
if ($is_logged_in) {
  // get the duration in minutes (time() is in seconds so we divide by 60 to get minutes) - and ceil() rounds the number with decimal to a whole number
  $duration_minutes = ceil((time() - $_SESSION['logged_in_time']) / 60);       
  $cost_per_min = 2/60; // get the cost per minute based on the $2 hourly rate
  $my_cost = $cost_per_min * $duration_minutes;
  if ($duration_minutes > (60 * 24) ) {
    // test to see if we need an 's' appended to our duration
    $s = ($duration_minutes/(60 * 24) > 1) ? "s" : "";
    $duration_display = toFixed($duration_minutes/(60 * 24), 1) . " day" . $s;
  } else if ($duration_minutes > 60) {
    $s = ($duration_minutes/60 > 1) ? "s" : "";
    $duration_display = ceil($duration_minutes/60) . " hour" . $s ;
  } else {
    // test to see if we need an 's' appended to our duration
    $s = ($duration_minutes > 1) ? "s" : "";
    $duration_display = $duration_minutes . " minute" . $s;
  }  
  $message = "You have been logged in " . $duration_display . " ($" . $my_cost . ")";
}
// in the above functions toFixed($value, 1) takes a number like 3.34567 and makes it 3.3
?>

html

<div class='cost_header'><?php echo $message?></div>

推荐阅读