php - 将计时器添加到简单的 php 登录时间
问题描述
我想知道如何在一个简单的 php 登录表单中添加一个计时器,以显示用户保持登录的时间(优先级)
如果你不介意,你能告诉我如何将时间乘以每小时的价格率吗
例如:Mr Q 登录 3 小时,价格为 2 美元,所以主页会在计时器旁边显示总计 6 美元
解决方案
使用会话变量跟踪持续时间。当用户登录时,记录时间并将其粘贴到会话变量中。这只会在登录时发生,并且在他们注销时会被删除。
每次刷新页面时,获取当前时间和会话时间戳之间的差异 - 然后进行乘法以获取成本。
<?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>
推荐阅读
- python - 从 sys.path 中删除用户站点目录,而 shebang 中没有“-s”
- jasper-reports - 通过其余 2 API 运行报告时如何设置数据适配器
- javascript - 有没有办法覆盖 Olark css?
- html - 如何将 ap 放在 div 的中心?
- python - Pygame - 出现黑屏
- vuejs2 - 在具有计算属性值的输入上使用 @input 或 @change
- sql - 查找字符串中特定数字的位置
- database - 将 obj 文件从服务器放入场景 Unity
- fish - 如何在鱼壳中获取数组大小?
- java - SolrException:打开新搜索器时出错