简体   繁体   English

Cookie或Javascript

[英]Cookie or Javascript

I am trying to make a countdown timer for a game. 我正在尝试为游戏制作倒数计时器。 And the problem is, when the user move to another page, then countdown cannot continue the remaining time. 问题是,当用户移动到另一个页面时,倒计时不能继续剩余的时间。 I am trying to set a cookie and session, but I have no idea about it. 我正在尝试设置cookie和会话,但我不知道它。

Cookies are sent back and forth with every HTTP request, hence should be avoided for storing unnecessary variables. Cookie随每个HTTP请求来回发送,因此应避免存储不必要的变量。

To maintain the timer on the server-side, a session is the best choice. 要在服务器端维护计时器,会话是最佳选择。 It will take care of the cookie business automatically, creating only the bare-minimum cookie overhead to keep track of the session. 它将自动处理cookie业务,仅创建最小的cookie开销以跟踪会话。 Session variables live on the server, and are connected to HTTP requests by unique cookies. 会话变量存在于服务器上,并通过唯一的cookie连接到HTTP请求。

Regarding your countdown timer: Since you cannot keep a function running on the server to keep flipping the bits, the best bet is to keep track of the end time. 关于倒数计时器:由于您无法在服务器上运行功能以保持翻转位,因此最好的办法是跟踪结束时间。

To initiate a session in PHP, use session_start() . 要在PHP中启动会话,请使用session_start() Then store your values in $_SESSION[] array, and they'll persist across requests. 然后将您的值存储在$_SESSION[]数组中,它们将在请求中保持不变。 Here's an example: 这是一个例子:

<?php
session_start();
if (!isset($_SESSION['endTime']))
{
    $_SESSION['endTime'] = time() + 60; // end time is 60 seconds from now
    echo "Started a new timer"
}
else if ($_SESSION['endTime'] > time())
{
    echo "Time left: " + ($_SESSION['endTime'] - time());
}
else
{
    echo "Time is up.";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM